2016-11-28 89 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