我有两个初学者程序,都使用'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)....
有人可以告诉我为什么这些程序有所不同吗?谢谢!
答案 0 :(得分:3)
在第二个示例中,用户没有机会在循环内输入新的猜测,因此a
和b
保持不变。
答案 1 :(得分: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()
答案 2 :(得分: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()
答案 3 :(得分:2)
如果不正确,您的第二个程序不允许用户重新输入猜测。将input
放入while循环中。
其他提示:不要像variable == True
那样进行检查,只需说while variable:
。