我想循环100次但不在循环中打印100次(Python)

时间:2013-06-11 17:24:35

标签: python loops random printing

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 个答案:

答案 0 :(得分:10)

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

在循环开始时询问他们!

for lp in range(100):
    guess = int(input('Guess number {0}:'.format(lp + 1)))
    ...

答案 1 :(得分: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."))

答案 2 :(得分:0)

你应该在循环中要求猜测:

while True:
    guess = int(raw_input("Guess: "))
    if guess == number:
        break
    if guess < number:
        print "Nah m8, Higher."
    else:
        print "Nah m8, lower."

答案 3 :(得分: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

这对你有用