Home > Back-end >  COin flipping - Prompt the user to play again
COin flipping - Prompt the user to play again

Time:03-04

I'm making a simple coin flipping game, but I want to add another line of code where the user can play again after, but I don't know where to start. I know I used while loops, but I don't really understand them too well.

import random 
def num_of_input():
    userName = input("Please enter your name: ")
    print("Hello "   userName   "!"   " This program simulates flipping a coin.")
    print()
    userWantsToPlay = input("Do you want to play this game? (Y/N): ")
    time_flip = ""
    print()
    while userWantsToPlay in ("Y", "y", "yes", "Yes", "yeah", "YES"):
        try:
            time_flip = int(input("How many times of flips do you want?: "))
        # if user enters a string it prompts them to type again    
        except ValueError:
            print("Please try again.")
            continue
        else:
            break
    return time_flip

def random_flip():
    return random.randint(0, 1)

def main():
    count_head=0
    count_tail=0
    times=num_of_input()
    while True:
        if count_head   count_tail == times:
            break
        else:
            if random_flip()==0:
                count_head =1
            else:
                count_tail =1
    print()   
    print("Of the "   str(times)   " times the coin was flipped...")
    print(str(count_head)   " came up Heads")
    print(str(count_tail)   " came up Tails")
main()

CodePudding user response:

https://stackoverflow.com/a/41718725/15537469

#infinite while loop
while True:
   main()
   restart = input('do you want to restart Y/N?')
   if restart.lower() == 'n'
       break  
   elif restart.lower() == 'y':
       continue

I have redone the code more simply

import random 

def random_flip():
    return random.randint(0, 1)

def starter():
    userName = input("Please enter your name: ")
    print(f"Hello {userName}! This program simulates flipping a coin.\n")
    
def main():
    count_head = 0
    count_tail = 0
    count = int(input("How many times of flips do you want?: "))
    for i in range(count):
        if random_flip()==0:
            count_head =1
        else:
            count_tail =1
    print(f"\nOf the {count} times the coin was flipped...")
    print(f"{count_head} came up Heads")
    print(f"{count_tail} came up Tails")
    
starter()
while True:
   main()
   restart = input('\nDo you want to restart Y/N?')
   if restart.lower() == 'n':
       break  
   elif restart.lower() == 'y':
       continue
  • Related