python - 无法让我有条件检查 str 或 int 的输入值并忽略 if 语句(Python 3.9)
问题描述
试图写一个简单的 if, elif 语句。我提示用户输入并且:如果输入是 int(),则运行 if seconds => 语句并开始倒计时。elif 输入是一个 str(),打印给用户输入一个 int()。
print("We're ready captain! How many seconds until launch?")
seconds = input()
isInputString = type(seconds) == str #yields True if seconds == str()
if isInputString == True: #tell the user to try again
print("I need a number Captain!")
seconds = input() #prompt a second input
else: #else it wasn't a str() and to proceed on with script
pass
目前,即使输入了 int(),脚本也会提示输入第二个输入。
这是由于我输入 if - else 语句的方式吗?
我觉得它应该求助于 else - 如果输入了 int() 则通过,但即使 isInputString == False 它仍会提示第二个分支 input()。
解决方案
您需要将类型转换为int
内部 atry..except
或使用该.isdigit()
方法。更好的方法:
print("We're ready captain! How many seconds until launch?")
while True:
try:
seconds = int(input())
except:
print("I need a number Captain!")
else:
break
print(seconds)
推荐阅读
- java - Java 是否有模棱两可的语法,需要有关标识符的更多信息?
- html-table - 如何在Angular 6的动态材料表中隐藏一列?
- angular - 在 Angular 中关闭全屏时不会调用转义函数
- sql - 如何在 DB2 中永久按列名对表进行排序
- azure-service-fabric - 将动态生成的端口从一个服务传递到同一应用程序中的另一个服务
- python - 我们如何自动知道开源软件是否存在任何新漏洞?
- javascript - 有什么方法可以动态禁用角度多选(cuppa labs)
- arduino - 开启直流电机的 PIR 传感器
- ios - 存档项目“错误:中止陷阱:6”时出现此错误
- php - Is there a way to pass a form request to a custom request to validate data