首页 > 解决方案 > 无法让我有条件检查 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()。

标签: pythonstringif-statementinteger

解决方案


您需要将类型转换为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)

推荐阅读