如果print语句重复很多次

时间:2014-04-17 12:48:06

标签: python loops if-statement

为什么太低,太高并且反复打印很多次?

这是我的代码:

import random
name = input("Hello there! What's your name?\n")
print("Hello there", name, ". Welcome to GUESS THE NUMBER GAME")
number = random.randint(1,100)
guess = int(input("Please guess a number"))
n=1
while n<10:
    if guess < number:
        print("Too low")

    elif guess > number:       
        print("Too high")

    elif guess == number:        
        print("Got it")

    n=n+1

3 个答案:

答案 0 :(得分:4)

您需要将<{1}} 移动到循环中,来自:

guess

为:

guess = int(input("Please guess a number"))
n=1
while n<10:
    if guess < number:
        print("Too low")

    elif guess > number:       
        print("Too high")

    elif guess == number:        
        print("Got it")

    n = n+1

此外,您可以简化:

n = 1
while n < 10:
    guess = int(input("Please guess a number"))
    if guess < number:
        print("Too low")

    elif guess > number:       
        print("Too high")

    elif guess == number:        
        print("Got it")

    n += 1

当用户做出正确的猜测时应该for _ in range(9): guess = int(input("Please guess a number")) ...

break

答案 1 :(得分:0)

这是你真正的缩进吗?

如果是的话:

while n<10:
    if guess < number:
        print("Too low")
    elif guess > number:       
        print("Too high")
    elif guess == number:        
        print("Got it")

,最后elif guess == number:可以只是else;)

编辑:我忘记了你的n ++和真正的问题:输入

这样:

while n<10:
    guess = int(input("Please guess a number"))
    n = n+1
    if guess < number:
        print("Too low")
    elif guess > number:       
        print("Too high")
    else:
        print("Got it")

并退出循环:

while n<10:
    guess = int(input("Please guess a number"))
    n = n+1
    if guess < number:
        print("Too low")
    elif guess > number:       
        print("Too high")
    else:
        print("Got it in "+n+" attempts.")
        n=11

答案 2 :(得分:0)

假设您提供的代码具有正确的缩进,那么因为n = n + 1语句不在while循环中。更正的代码是:

import random
name = input("Hello there! What's your name?\n")
print("Hello there", name, ". Welcome to GUESS THE NUMBER GAME")
number = random.randint(1,100)
guess = int(input("Please guess a number"))
n=1
while n<10:
    if guess < number:
        print("Too low")

    elif guess > number:       
        print("Too high")

    elif guess == number:        
        print("Got it")

    n=n+1

一条建议(假设您使用的是Python 2.X):使用raw_input()代替input,因为raw_input会自动将输入解析为字符串,而input 1}}允许用户注入任意python代码。

ETA:正如其他人所指出的,猜测语句(guess = int(input("Please guess a number")))应该移入while循环,如果猜测正确则使用break语句。