我已经编写了一个程序,要求用户提供邮政编码。这是代码:
_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 :(得分:2)
它不会达到else
条款。如果len(_code)
为5,则表示您未进入此
while len(_code) != 5:
所以你没有进入那里的if/else
我想你只想摆脱那句话。
答案 1 :(得分:1)
看着你的代码,似乎你应该简单地删除else
块并将其移到while
块之外。这是因为while
循环旨在不断询问用户输入,只要他没有输入5
。
收到5
后,他 不在<{1}}区域内。试着写一下这个,
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))
/ _code = str(input('Enter your post code: '))
全部移到if
之外。像这样的东西会起作用,
elsif
答案 2 :(得分: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