Home > Software design >  Is there something wrong with the try and except statements that caused the error?
Is there something wrong with the try and except statements that caused the error?

Time:03-02

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

CodePudding user response:

The variable time_flip can only be referred to within the try block. Variables first assigned within try blocks cannot be referred to outside of the try block.

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

CodePudding user response:

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
  • Related