简体   繁体   中英

While Loop Number Game in Python

I am attempting to make a very basic number game in Python. When I give the program input it just loops and keeps asking for input instead of displaying the given print statements and completing the code.

    import random
    win = False
    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

    while not win:
    guess = input("Guess a number between 1 and 10:")
    num = random.choice(numbers)
    if num > int(guess):
    print("Too high! Try again.")
    if num < int(guess):
        print("Too low! Try again.")
    if num == int(guess):
     win = True
    print("You win!")

First of all you can take an input like this. int(input()) , that way you don't always have to convert your variable. Secondly, you have your <, > symbols mixed up. And your random.choice() should be outside your loop or it will keep choosing new numbers.

Your code should look like this.

import random
win = False
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
num = random.choice(numbers)
while not win:
    guess = int(input("Guess a number between 1 and 10:"))
    if num < guess:
        print("Too high! Try again.")
    if num > guess:
        print("Too low! Try again.")
    if num == guess:
        win = True
print("You win!")

Some remarks:

  1. You're creating a new num every time the loop is run, so the user will have no clue if the number is low or high than the expected number since it's being created on every attempt.

  2. You can use elif s and else s to avoid unnecessary checks.

  3. I don't know if it's a copy-paste error but you must also fix the identation of your code.

Fixed code:

import random
win = False
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# 1. Create the expected number outside the loop
num = random.choice(numbers)
while not win:
    # Just convert the input as integer if you won't use it as string
    guess = int(input("Guess a number between 1 and 10:"))
    
    # 2. Use elifs and elses
    if num > guess:
        print("Too high! Try again.")
    elif num < guess:
        print("Too low! Try again.")
    else:
        win = True
        print("You win!")

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