Issue
I'm trying to make a basic coin flipping simulator. And ask the user for their name and greet them. Then ask if they want to play the game. But when they enter something other than "Y"
, it gives this error message: UnboundLocalError: local variable 'time_flip' referenced before assignment
how can I fix that and instead it prints a goodbye message. And ask them again if they want to keep playing.
import random
def num_of_input():
userName = input("Please enter your name: ")
print("Hello " + userName + "!" + " This program simulates flipping a coin.")
userWantsToPlay = input("Do you want to play this game? (Y/N): ")
while userWantsToPlay in ("Y", "y"):
try:
time_flip = int(input("How many times of flips do you want? "))
except:
print("Please try again.")
continue
else:
break
return time_flip
There is more code, but I shortened it to the part with errors here's the full program: https://replit.com/@Blosssoom/coinpy?v=1#main.py
Solution
The assignment of time_flip
may not complete if there is an error transforming the input to an integer.
To resolve, assign to time_flip
before the try
block:
import random
def num_of_input():
userName = input("Please enter your name: ")
print("Hello " + userName + "!" + " This program simulates flipping a coin.")
userWantsToPlay = input("Do you want to play this game? (Y/N): ")
time_flip = None
while userWantsToPlay in ("Y", "y"):
try:
time_flip = int(input("How many times of flips do you want? "))
except:
print("Please try again.")
continue
else:
break
return time_flip
Answered By - BrokenBenchmark
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.