-2

Ok so I want to make a very very very very very simple coin flipping program and I want to make it so the player can choose if to close after the coin flipped or if to flip again. This is the code I used, the person can type either 1 or 2, and choose if to flip again or if to close the program, I tried using open("Coinflip.py) but it didn't do anything. What should I do?

import random 
import time  
flip = random.randint(1, 2)  
if flip == 1:     
    print("The coin landed heads")  
if flip == 2:     
    print("The coin landed tails")   
print('') 
print("")  
time.sleep(1)  
choice = int(input("Type 1 to exit or 2 to flip again and press enter "))  
if choice == 1:     
    exit()  
elif choice == 2:     
    open("Coinflip.py") 
input()
Mime
  • 1,142
  • 1
  • 9
  • 20
  • You want to run another python process, from an already running python process? This is called Multiprocessing https://docs.python.org/3/library/concurrent.futures.html – Tom McLean Aug 31 '22 at 12:58
  • @TomMcLean this might be overkill. Instead it sounds like they should instead use a [`while`](https://docs.python.org/3/tutorial/controlflow.html)-loop, to repeat the same code again. – Mime Aug 31 '22 at 13:04
  • 1
    @Mime Yep, no idea without any code though – Tom McLean Aug 31 '22 at 13:05
  • 2
    Please add your code – Lenntror Aug 31 '22 at 13:06
  • @Lenntror `import random import time flip = random.randint(1, 2) if flip == 1: print(" The coin landed heads") if flip == 2: print(" The coin landed tails") print('') print("") time.sleep(1) choice = int(input(" Type 1 to exit or 2 to flip again and press enter ")) if choice == 1: exit() elif choice == 2: open("Coinflip.py") input()` – Daniele Krivitskiy Aug 31 '22 at 13:10
  • Does this answer your question? [How do I repeat the program in python](https://stackoverflow.com/questions/41365922/how-do-i-repeat-the-program-in-python). Besides that, you should read the [python tutorial](https://docs.python.org/3/tutorial/) – Mime Aug 31 '22 at 13:15
  • btw i couldnt add an image – Daniele Krivitskiy Aug 31 '22 at 13:16
  • You should never add the code as image, instead add it as text in the question by surrounding it with tripple backticks. Please also read [How to ask](https://stackoverflow.com/help/how-to-ask) – Mime Aug 31 '22 at 13:18

1 Answers1

2

You can use a function and a while loop to continuously ask for coin flips:

import random
import time

def coin_flip():
    flip = random.randint(1, 2)
    if flip == 1:
        print("The coin landed heads")
    if flip == 2:
        print("The coin landed tails")
    time.sleep(1)


def main():
    while True:
        choice = int(input("Type 1 to exit or 2 to flip again"))
        if choice == 1:
            break
        elif choice == 2:
            coin_flip()


if __name__ == "__main__":
    main()

technically you don't need a function, but lets use one anyway

Tom McLean
  • 5,583
  • 1
  • 11
  • 36