简体   繁体   中英

How do you start a Python game loop?

I have this very simple console game and I would like to restart the loop after the user answers a question but something doesn't seem to work properly.

import random

random_number = random.randrange(0, 500)
chosen_number = int(input("Please pick a number: "))
gameOn = 1

while gameOn == 1:
    if chosen_number == 500 or chosen_number <= 0 :
        print("Number must be below 500 and above 0.")
        print(random_number)
        chosen_number = int(input("Please pick a number: "))
        continue
    if chosen_number > random_number:
          print("Too high")
          chosen_number = int(input("Please pick a number: "))
    elif chosen_number < random_number: 
          print("Too low")
          chosen_number = int(input("Please pick a number: "))
    else:
        print("Congratulations, you guessed right. The number was " + str(chosen_number) + ".")
        break

    answer = input("Do you want to play again? Y/N ")

    if answer == "Y" or "y" or "yes":
        gameOn = 0
    else:
        print("Goodbye!")

When you ask to play again you are setting gameOn to be 0 (as gameOn needs to be 1), which will exit the loop, your code should look like this

if answer in ("Y", "y", "yes"):
    print("Starting again")
else:
    print("Goodbye!")
    gameOn = 0

for further clarification since you are choosing a number each game you need to put that into the loop as well


import random
gameOn = 1

while gameOn == 1:
    random_number = random.randrange(0, 500)
    chosen_number = int(input("Please pick a number: "))
    if chosen_number == 500 or chosen_number <= 0 :
        print("Number must be below 500 and above 0.")
        print(random_number)
        chosen_number = int(input("Please pick a number: "))
        continue
    if chosen_number > random_number:
          print("Too high")
          chosen_number = int(input("Please pick a number: "))
    elif chosen_number < random_number: 
          print("Too low")
          chosen_number = int(input("Please pick a number: "))
    else:
        print("Congratulations, you guessed right. The number was " + str(chosen_number) + ".")
        break

    answer = input("Do you want to play again? Y/N ")

    if answer in ("Y", "y", "yes"):
        print("Starting again")
    else:
        print("Goodbye!")
        gameOn = 0

The loop will automatically restart if you don't change any of the variables. So I would change your if else statement to just an if statement that says:

if answer.lower() != "y" or answer.lower() != "yes":
    break

but in order for the game to be re-run properly and change the random number variable you need to re-execute the entire program which you can do by putting the program in a function then putting the function and the if statement in that loop for example:

import random
def runGame():
    random_number = random.randrange(0, 500)
    chosen_number = int(input("Please pick a number: "))
    running = True

    while running:
        if chosen_number == 500 or chosen_number <= 0 :
            print("Number must be below 500 and above 0.")
            print(random_number)
            chosen_number = int(input("Please pick a number: "))
            continue
        if chosen_number > random_number:
            print("Too high")
            chosen_number = int(input("Please pick a number: "))
        elif chosen_number < random_number: 
            print("Too low")
            chosen_number = int(input("Please pick a number: "))
        else:
            print("Congratulations, you guessed right. The number was " + str(chosen_number) + ".")
        break

    
while gameOn == 1:
    runGame()
    answer = input("Do you want to play again? Y/N ")
    if answer.lower() != "y" or answer.lower() != "yes":
        gameOn = 0

You can do a simple thing, just put the whole code in a function and when you want to restart just call the function

Look at the code below:

import random

def game():
  random_number = random.randrange(0, 500)
  chosen_number = int(input("Please pick a number: "))

  while True:
      if chosen_number == 500 or chosen_number <= 0 :
          print("Number must be below 500 and above 0.")
          print(random_number)
          chosen_number = int(input("Please pick a number: "))
          continue
      if chosen_number > random_number:
            print("Too high")
            chosen_number = int(input("Please pick a number: "))
      elif chosen_number < random_number: 
            print("Too low")
            chosen_number = int(input("Please pick a number: "))
      else:
          print("Congratulations, you guessed right. The number was " + str(chosen_number) + ".")
          break

      answer = input("Do you want to play again? Y/N ")

      if answer.lower() == "y" or "yes": # Lower() is used for changing the whole string to lowercase
          game()
      else:
          print("Goodbye!")

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