简体   繁体   中英

Python 3: Can't exit a "while" loop

The program asks:

would you like to repeat the execution? (Y/N)

If user enters "Y" or "N", the program starts again or exit, respectively.

If user enters something different from "Y" or "N", the program should print "I can't understand you, bye!"

I defined a function with the operations that I'm interested in. I call this function from a while loop. If user enters "Y" it calls the function, if user enters "N" it prints a message and exit, if user enters another character it prints the error message.

It works OK when I enter "Y" or "N", however it calls the function if I enter any other character such as "Z".

Below is my code. Thank you!

import random
import time

def Intro():
    
    print("some text here") 
    print("select a cavern (1 ó 2)")

def juego():
    dragon = random.randint(1,2)
    cueva = int(input())

    print("bla bla")
    time.sleep(2)
    print("bla bla bla")
    time.sleep(2)
    print("bla")
    time.sleep(2)
    
    if cueva == dragon:
        print("you win")
        print("start again? (Y/N)")
        print()
    else:
        print("you lose")
        print("start again? (Y/N)")
        print()
    
Intro()
juego()

seguir = input()
print()

while seguir == "Y" or "y":
    Intro()
    juego()
    seguir = input()
    print()
    if seguir == "N" or "n":
        print("Thanks for playing")
        break
    if seguir != "S" and seguir != "s" and seguir != "N" and seguir != "n":
        print("I can't understand you, bye!")
        break

Your while loop is only working when the user initially inputs a Y. If the user does not input the Y before the while loop, the check evalueates to false so the while loop never gets run. Dont get input before the while loop, set seguir to 'Y' at the begining so you can actually enter it.

You should try like:

if seguir in ["N", "n"]: 
    print("Thanks for playing") 
    break

if seguir.lower() == "n": 
    print("Thanks for playing") 
    break

want to help~

ref: How to test multiple variables for equality against a single value?

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