2010-03-16 43 views
-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).... 

有人可以讓我知道爲什麼這些程序是不同的?謝謝!

+1

「while function」?你的意思是「聲明」嗎? – 2010-03-16 10:06:37

+0

'== True'永遠不是正確的路要走。而不是'if a == True:',總是比較喜歡'如果a:'。 – 2010-03-16 16:15:34

回答

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() 
+0

明白了,謝謝!沒有考慮變量的定義。 – Jeremy 2010-03-16 08:49:37

3

在第二個示例中,用戶沒有機會在循環內輸入新的猜測,因此ab保持不變。

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

你的第二個程序不允許用戶重新輸入自己的猜測,如果它是不正確的。將input放入while循環中。

附加提示:不要使支票像variable == True,只是說while variable: