即使 if 语句为 true,Python 仍会检查 elif 语句

问题描述 投票:0回答:1

我有一系列

if
/
elif
语句,用于检查变量
n
(类型字符串),该变量可以采用
"Teacher"
"1"
"2"
等值:

Students = [Anna, Betty, Charles] # List of objects "Student"

n = input("insert student number: ")

if n == "Teacher":
    print(Teacher.Data)

elif Students[int(n)].mark > 5:
    print(Students[int(n)].Data)

else:
    print("non valid student")

Python 似乎会检查

elif
语句,即使第一个
if
语句为真,也会生成
invalid literal for int()
错误。有没有办法在维护条件语句的同时避免此错误?

python
1个回答
0
投票

您可以使用 .isnumeric() 内置函数。这是链接:https://www.w3schools.com/python/ref_string_isnumeric.asp

在你的情况下应该是:

Students = [Anna, Betty,Charles] # List of objects "Student"

n = input("insert student number: ")

if n == "Teacher":
    print(Teacher.Data)

elif n.isnumeric() and Students[int(n)].mark > 5:
    print(Students[int(n)].Data)

else:
    print("non valid student")
© www.soinside.com 2019 - 2024. All rights reserved.