简体   繁体   中英

Python if statement not working inside function

I'm trying to make a guess the number game in python. However, in the again() function I cannot seem to get the if statement to run.

When I don't use the again function and copy and paste all the code in the respective positions, it works fine. However when I use the again function, the "play again?" question is asked but the if statement is ignored, causing the while loop to continue endlessly. I have tried using the global function but on the second time I input a guess, it comes up with TypeError: 'str' object is not callable .

import random

def guess():
    global num
    num = random.randint(1,3)
    guessat  = input("Out of 1 to 3, which number do you guess? ")
    return(guessat)

def again():
    global again
    again = input("Play again? ")
    if again in ["y","yes"]:
        guessing = True
    else:
        guessing = False

print("Welcome to Guess the Number!")

guessing = True

while guessing:
    guessy = guess()
    guessy = int(guessy)
    if guessy == num:
        print("You got it right!")
        again()

    elif guessy != num:
        print("Wrong number!")
        again()
quit()

When I input "no" or anything else for the question "Play Again?" I expect the program to exit the while loop and quit.

The if/else statement works perfectly, the problem is elsewhere. More specifically, there are 2 things wrong in your code.

  1. the use of the same name again for both the variable and the function, you should use different names.

  2. the guessing variable should be global as well otherwise the while-loop will never see it changing.

Try this:

def again():
    global guessing
    _again = input("Play again? ")
    if _again in ["y","yes"]:
        guessing = True
    else:
        guessing = False

One more thing. As others commented already, the use of global variables is generally not a good idea, is better to have your function return something instead.

Avoid naming your variable again inside a function called again . However in regards to your infinite loop problem, you set local variable guessing inside the again function, no the global variable guessing , hence the variable checking the while loop condition is not affected at all. Might I suggest:

def again():
    global guessing
    play_again_input = input("Play again? ")
    if play_again_input in ["y","yes"]:
        guessing = True
    else:
        guessing = False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM