2016-11-28 131 views
1

我寫了一個程序,要求一個職位代碼的用戶。下面的代碼:缺少打印語句

_code = str(input('Enter your post code: ')) 

_exit = True 
while _exit: 
    print(_code) 
    while len(_code) != 5: 
     if len(_code) > 5: 
      print("to long") 
      _code = str(input('Enter your post code: ')) 
     elif len(_code) < 5: 
      print("to short") 
      _code = str(input('Enter your post code: ')) 
     else: 
      print('post code is: ' + str(_code)) 
    break 

問題是,當我開始它工作正常的程序,但是當輸入已經得到了len(_code)等於5應該跳到else語句,但事實並非如此。它只是停止運行程序(中斷)。我希望該程序打印:

郵編是:XXXXX

我已經下載了我的手機上QPython 1.2.7,還有它完美的作品!

+0

由於沒有縮進代碼是不可讀的。請使用代碼塊(四個空格)正確格式化它 – martianwars

+0

您可能有縮進問題,而您的移動電話上沒有該縮進問題。即使不是最佳的,這個代碼也應該可以工作。 –

+0

適用於我的電腦。 –

回答

2

它不會打else條款。如果len(_code)是5你沒有進入這個

while len(_code) != 5: 

所以你沒有得到進入if/else在那裏

我覺得你只是想擺脫,雖然語句。

0

else子句是while循環所以將不執行內部時LEN(_CODE)= 5。 如果你像下面那樣重構你的代碼,它應該可以工作。

_code = str(input('Enter your post code: ')) 

_exit = True 
while _exit: 
    print(_code) 
    while len(_code) != 5: 
     if len(_code) > 5: 
      print("too long") 
      _code = str(input('Enter your post code: ')) 
     elif len(_code) < 5: 
      print("too short") 
      _code = str(input('Enter your post code: ')) 
    print('post code is: ' + str(_code)) 
    break 
1

看着你的代碼好像你應該簡單地擺脫else塊和移動它的while塊之外。這是因爲while循環的目的是不斷地問用戶對輸入只要他沒有輸入5

在收到5時,他應該不是while塊內。嘗試,而不是寫這篇文章,

while len(_code) != 5: 
    if len(_code) > 5: 
     print("too long") 
     _code = str(input('Enter your post code: ')) 
    elif len(_code) < 5: 
     print("too short") 
     _code = str(input('Enter your post code: ')) 
# The print is no longer inside an `else` block 
# It's moved outside the loop 
print('post code is: ' + str(_code)) 

隨着進一步的改進,你可以在if/elsif向外移動的_code = str(input('Enter your post code: '))一起。像這樣的東西會工作,

# Initialize to zero length 
_code = "" 
while len(_code) != 5: 
    # Executed each time at beginning of `while` 
    _code = str(input('Enter your post code: ')) 
    if len(_code) > 5: 
     print("too long") 
    elif len(_code) < 5: 
     print("too short") 
print('post code is: ' + str(_code)) 
+0

Thaks給大家的答案,尤其是對martianwars! 現在,它的偉大工程,我一直在想,爲什麼我以前的代碼工作在我的移動很好,但不是在我的電腦?我明天就明白這一點,現在是時候用我的while語句睡覺了;) – vadelbrus

+0

不要忘記接受正確的答案。別客氣! – martianwars