0

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

BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
  • A blanket `except` is [basically always wrong.](https://stackoverflow.com/questions/54948548/what-is-wrong-with-using-a-bare-except) The error message actually tells you one of the reasons. Think about what would cause the variable to be unset, and maybe change your code to either not try to access the variable when that happens, or ensure that it is set when it needs to be. – tripleee Mar 02 '22 at 06:22
  • If *userWantsToPlay* is anything other than 'Y' or 'y' then *time_flip* will be undefined – DarkKnight Mar 02 '22 at 06:48

2 Answers2

1

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
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
  • I haven't really learned what None is. Is there another way to do that? –  Mar 02 '22 at 06:27
  • 1
    You can assign `time_flip` to whatever initial value you want. If you don't like `None`, use the empty string instead (or any string of your choice). Just make sure you have _some_ assignment outside of the `try` block. – BrokenBenchmark Mar 02 '22 at 06:29
  • Could you maybe show an example? –  Mar 02 '22 at 06:30
  • 1
    `time_flip = ""`? Again, _what_ you assign to `time_flip` initially is not worth fussing over, because it's going to get overwritten by whatever is sent through `input()`. The _existence_ of an assignment statement outside of the `try` block is what you should be concerned about. – BrokenBenchmark Mar 02 '22 at 06:31
  • That works, but I wanted to print a goodbye message instead. And possibly make another while loop to ask the user if they want to play again. But not sure where to put it. –  Mar 02 '22 at 06:33
  • 1
    That would be a great topic for another question :) – BrokenBenchmark Mar 02 '22 at 06:34
  • I'm pretty sure that's what I asked in my question. ;-; –  Mar 02 '22 at 06:36
  • Don't encourage them to post more questions. Look at their recent posting history. – tripleee Mar 02 '22 at 06:38
  • @tripleee I'm in a double bind here. This question asks for multiple different things (resolving an error _and_ adding an extra message) which goes against SO guidelines. The normal procedure is to tell them to separate their issues into discrete questions. On the other hand, this is a (sort of) duplicate of [this question](https://stackoverflow.com/questions/71316726/coin-flipping-simulator) that they posted four hours ago. I don't know, this is a pretty unusual situation. – BrokenBenchmark Mar 02 '22 at 06:41
  • Yeah, but probably just tell them to slow down until they figure out how the site works. – tripleee Mar 02 '22 at 06:42
  • Fair enough. At this point it might be good to vote to close as a duplicate or for needing more focus, but I've already answered and the dupe target I just gave isn't _quite_ right. – BrokenBenchmark Mar 02 '22 at 06:46
0

If people don't type y or Y, the while loop will never run. This cause that every variables in the while loop will never ba created. You want to return time_flip, but because it supposes to be made in the while loop (), it won't be created -> local variable 'time_flip' referenced before assignment (self-explained).

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 = 0 #None or anything
    while userWantsToPlay in ("Y", "y"):
        try:
            time_flip = int(input("How many times of flips do you want? "))
        except:
            print("Please try again.")
            continue
    return time_flip
BrainFl
  • 127
  • 1
  • 8