-1

我有两个初学者程序,都使用'while'函数,一个正常工作,另一个让我陷入循环。第一个程序是这样的;

num=54
bob = True
print('The guess a number Game!')


while bob == True:
    guess = int(input('What is your guess?  '))

    if guess==num:
        print('wow! You\'re awesome!')
        print('but don\'t worry, you still suck')
        bob = False
    elif guess>num:
        print('try a lower number')
    else:
        print('close, but too low')

print('game over')``

它给出了可预测的输出;

The guess a number Game!
What is your guess?  12
close, but too low
What is your guess?  56
try a lower number
What is your guess?  54
wow! You're awesome!
but don't worry, you still suck
game over

但是,我也有这个程序,它不起作用;

#define vars
a = int(input('Please insert a number: '))
b = int(input('Please insert a second number: '))

#try a function
def func_tim(a,b):
    bob = True
    while bob == True:
        if a == b:
            print('nice and equal')
            bob = False
        elif b > a:
             print('b is picking on a!')
        else:
            print('a is picking on b!')
#call a function
func_tim(a,b)

哪些输出;

Please insert a number: 12
Please insert a second number: 14
b is picking on a!
b is picking on a!
b is picking on a!
...(repeat in a loop)....

有人可以让我知道为什么这些程序不同吗?谢谢!

4

4 回答 4

3

在第二个示例中,用户没有机会在循环内输入新的猜测,因此ab保持不变。

于 2010-03-16T08:43:11.623 回答
2

在第二个程序中,如果它们不相等,您永远不会给用户选择两个新数字的机会。将您从用户那里获得输入的行放在循环中,如下所示:

#try a function
def func_tim():
    bob = True
    while bob == True:
        #define vars
        a = int(input('Please insert a number: '))
        b = int(input('Please insert a second number: '))

        if a == b:
            print('nice and equal')
            bob = False
        elif b > a:
             print('b is picking on a!')
        else:
            print('a is picking on b!')
#call a function
func_tim()
于 2010-03-16T08:43:27.690 回答
2

在您的第二个程序中,如果b > a,您将返回循环,因为bob仍然是true。您忘记要求用户再次输入..尝试这种方式

  def func_tim():
    while 1:
       a = int(input('Please insert a number: '))
       b = int(input('Please insert a second number: '))
       if a == b:
           print('nice and equal')
           break
       elif b > a:
           print('b is picking on a!')
       else:
           print('a is picking on b!')


func_tim()
于 2010-03-16T08:44:39.277 回答
2

如果不正确,您的第二个程序不允许用户重新输入他的猜测。放入inputwhile循环。

附加提示:不要像 那样做检查variable == True,只说while variable:

于 2010-03-16T08:44:53.930 回答