初学Python - 卡在循环中

-1 投票
4 回答
4741 浏览
提问于 2025-04-15 20:28

我有两个初学者程序,都是用的'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 个回答

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()
4

在第二个例子中,用户没有机会在循环里输入新的猜测,所以 ab 的值保持不变。

3

在第二个程序中,你没有给用户机会去选择两个新的数字,如果这两个数字不相等的话。把获取用户输入的那几行代码放到循环里面,像这样:

#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()

撰写回答