python - 如何在不停止代码的情况下继续在 python 中请求有效输入
问题描述
嗨,我试图让我的代码要求输入,直到输入正确的值。如果输入正确,则继续执行其他任务。否则将再次提示用户。我尝试使用 Try/Except,但无法正确使用。我有这个:
while True:
try:
radius = float(input("Enter radius: "))
if radius > 1 and radius < 0:
break
print("Radius must be between 0 and 1. Try again: \n")
except Exception as e:
print(e)
finally:
print( 'ok lets go on')
### more tasks are performed and stuff ###
为了继续,用户必须输入一个介于 0 和 1 之间的浮点半径。否则它会一直询问。我还是新手,所以感谢您的耐心等待!
解决方案
while True:
try:
radius = float(input("Enter radius: "))
if radius < 1.0 and radius > 0.0:
break
print("Radius must be between 0 and 1. Try again: \n")
except Exception as e:
print(e)
finally:
print('ok lets go on')
### more tasks are performed and stuff ###
只要纠正运营商,它就会运作良好
前
if radius > 1 and radius < 0 :
后
if radius < 1.0 and radius > 0.0:
输出
Enter radius: 0.9
ok lets go on
Process finished with exit code 0
推荐阅读
- laravel - Laravel Eloquent - 不要返回关系
- rxjs - RxJs Subject 让我们先处理新的订阅
- forms - symfony 表单自定义选择类型小部件名称
- r - 如何为 R shinyWidgets > prettyToggle > label_on(和 label_off)换行文本
- matlab - 在调试模式下在命令窗口中选择性地显示标量值
- javascript - 查找引用为数字的单个 google 工作表位置
- json - 带有数据类的 Kotlin Gson
- php - 通过调用 php 函数动态更改内联 css
- neural-network - 神经网络中“节点”和“输入”之间的区别
- elasticsearch - Elasticsearch - 从结构中删除字段