I have two begininer programs, both using the 'while' function, one works correctly, and the other gets me stuck in a loop. The first program is this;
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')``
and it gives the p开发者_如何学JAVAredictable output of;
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
However, I also have this program, which doesn't work;
#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)
Which outputs;
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)....
Can someone please let me know why these programs are different? Thank you!
In the second example, the user doesn't get a chance to enter a new guess inside the loop, so a
and b
remain the same.
In the second program you never give the user a chance to pick two new numbers if they're not equal. Put the lines where you get input from the user inside the loop, like this:
#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()
in your 2nd program, if b > a
, you will go back to the loop because bob
is still true
. You forgot to ask the user to input again.. try it this way
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()
Your second program doesn't allow the user to reenter his guess if it's not correct. Put the input
into the while loop.
Additional hint: Don't make checks like variable == True
, just say while variable:
.
精彩评论