简体   繁体   中英

How do I loop this code after it ends and how do I get the Y/N part of the code to work?

Basically what i need is to have my code run again from the top after the player wins and is asked if he wants to continue. I also need help on how to do that. I want to make the code to start over when you choose yes and stop if you choose no

from random import *

a = randint(0,20)
user_input = ""
user_input2 = ""
while True:
   if a != user_input:
       user_input = int(input("Pick a number or die: \n"))
   print(user_input, a)
   if user_input < a:
       print("Aim higher")
   elif user_input > a:
       print("Bit lower mate")
   else:
       break

while True:
   if a == user_input:
       user_input2 = raw_input("Up for another try:(Y/N)?")
   if user_input2.lower() == 'N' or 'n':
       break
       print("Lets see if you re so lucky again.")
   if user_input2.lower() == 'Y' or 'y':
       pass
       print("No shame in being a coward")
   else:
       print("That is wrong")
       break




As your code is now, it loops through the first part (the game), then separately loops through the second part (the prompt). So when you say yes to play again, it just keeps asking if you want to play again.

You'll want to put the first loop inside of a main loop and get rid of the else statement in the second loop. Hopefully the comments make sense

You should have any print statements before the break otherwise the code will never reach that point. (eg after this if statement user_input2.lower() == 'N' or 'n': )

I think you have the Yes and No prompts mixed up as well. Play again Yes means, they will play again.

from random import *

a = randint(0,20)
user_input = ""
user_input2 = ""
while True:     #Loop for prompt and game
    user_input = ""     #Gets reset each time
    while True:     #Loop for just game
        if a != user_input:
            user_input = int(input("Pick a number or die: \n"))
        print(user_input, a)
        if user_input < a:
            print("Aim higher")
        elif user_input > a:
            print("Bit lower mate")
        else:
            break

    if a == user_input:
        user_input2 = raw_input("Up for another try:(Y/N)?")
    if user_input2.lower() == 'N' or 'n':
        print("No shame in being a coward")     #Quit game
        break
    if user_input2.lower() == 'Y' or 'y':
        print("Lets see if you re so lucky again.")     #Play again
        pass
    else:
        print("That is wrong")      #Bad or no input
        break

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