python - 清理 try 和 except 语句
问题描述
嗨,我正在制作一个代码,用户需要在其中输入一个 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 中,try/except 是关于处理异常的。在您的代码中,我没有看到任何异常被引发。使用 while 循环来确保用户输入有效数字怎么样?就像是:
while True:
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:
print ('\nPlease enter a valid number.')
推荐阅读
- json - Couchbase 的 Spring 数据 - java.lang.IllegalArgumentException:JsonArray 不支持的类型:
- python - 如何替换 A 列中 B 列等于值的值?
- javascript - 数据表发送当前页码
- c# - 如何在 C# 中使用 UserPrincipal 获取 Active Directory 中的地址详细信息
- android - 获取用户备份数据的唯一标识符
- google-apps-script - 选择下拉菜单中的名称时填写模板表
- azure - 如何在 Azure Function 中为 TelemetryConfiguration 使用依赖注入
- go - 如何将参数传递给 dlv 调试
- python - 我如何在 kivy 的 gui 中顺利加载文本
- unity3d - Unity - 如何在运行时更改 AnimationClip KeyFrame 值