【发布时间】:2020-06-08 13:56:33
【问题描述】:
您好,我正在制作一个代码,用户需要在其中输入一个 0-255 之间的数字,所以我希望尝试使用,除非他们输入一个字母和一个 if 语句,如果他们输入0-255 以外的数字。我写的没有错误,但看起来很乱,因为我必须两次调用输入等等。任何想法如何清理它/使它更短和更容易阅读。
try:
user_input = int(input('Enter a number between 0 and 255 to be converted to 8-bit binary: '))
if user_input > 0 and user_input < 255:
break
else:
user_input = int(input('\nEnter a number between 0 and 255 to be converted to 8-bit binary: '))
except:
print ('\nPlease enter a valid number.')
【问题讨论】:
标签: python python-3.x while-loop try-except