6
for lp in range(100):
    if guess == number:
        break
    if guess < number:
        print "Nah m8, Higher."
    else:
        print "Nah m8, lower."

这是我被告知为基本计算类编写的一些基本代码。我的目标是制作一个简单的“游戏”,用户必须猜测计算机选择的随机数(1-100)这是代码的一小部分,我想继续检查猜测是否等于,低于或高于该数字;但是如果我在下面放一个打印语句,它将打印文本 100 次。我怎样才能消除这个问题?

提前致谢。

4

4 回答 4

12

好像你省略了猜测阶段。程序在哪里要求用户输入?

在循环开始时询问他们!

for lp in range(100):
    guess = int(input('Guess number {0}:'.format(lp + 1)))
    ...
于 2013-06-11T17:27:09.443 回答
1

每次循环都需要获得一个新的输入;否则你只是继续检查同样的事情。

for lp in range(100):
    if guess == number:
        break
    if guess < number:
        # Get a new guess!
        guess = int(raw_input("Nah m8, Higher."))
    else:
        # Get a new guess!
        guess = int(raw_input("Nah m8, lower."))
于 2013-06-11T17:27:37.663 回答
0

您应该要求在循环内进行猜测:

while True:
    guess = int(raw_input("Guess: "))
    if guess == number:
        break
    if guess < number:
        print "Nah m8, Higher."
    else:
        print "Nah m8, lower."
于 2013-06-11T17:27:34.187 回答
0
import random
number = 0

x = []
while number < 100:
    guess = random.randint(1,100)

    if number < guess:
        print(f 'Number {number} is less than guess {guess}')
    elif number > guess:
        print(f 'Number {number} is greater than guess {guess}')
    number += 1

这对你有用

于 2021-06-24T07:23:55.540 回答