python 类型错误>=在'str'和'int'的示例之间不支持[重复]

mzaanser  于 2023-04-04  发布在  Python
关注(0)|答案(1)|浏览(112)

此问题在此处已有答案

How can I read inputs as numbers?(10个答案)
5年前关闭。
我已经写出了我的代码,但我一直在if personsAge >= 1上收到错误消息。
下面是错误:
类型错误〉=在'str'和'int'的示例之间不支持
每次我运行我的程序时都会发生这种情况。我不知道我做错了什么。任何帮助都非常感谢。
下面是我的代码:

# Purpose
''' This program classifies a person to a certain group based on their age'''
#=================================================================================
# Initialize variables(used for processing data)
ageGroup =""; #specify data as empty string
personsAge =""; #specify data as float /real
#====================================================================================

# Input Statements
fullName = str(input("<Enter your full name>"));
personsAge = str(input("<Enter your age>"));

#==========================================================================
'''nested if statements to determine a person's age group.'''

# Using the Nested If eliminates the need to check all if statements
# Once the criteria has been met, control is transferred to the statement
# following the last if Statement. However, the IF/ELSE must be aligned in same column

if (personsAge <=1) and (personsAge >0):
    ageGroup = "Infant.";

elif (personsAge >=1) and (personsAge <=13):
    ageGroup = "Child.";

elif (personsAge >=13) and (personsAge <=20):
    ageGroup = "Teenager.";

elif (personsAge >=20):
    ageGroup = "Adult.";
#====================================================================================
#Output Statements
print();
print("My name is " + fullName);
print("My age is " + personsAge);

#=================================================================
# Print Age group
print(fullName + "is an " + ageGroup);
print("=" * 80);
#===============================================================================
#End program
wnavrhmk

wnavrhmk1#

您正在将输入转换为字符串而不是整数。

使用int()将输入转换为整数:

personsAge = int(input("<Enter your age>"));

然后你就可以将它与其他整数进行比较。
每次将personsAge与字符串连接时,不要忘记将personsAge整数转换为str()字符串。示例:

print("My age is " + str(personsAge));

在不能保证用户输入是所需类型的情况下,添加错误处理是一种好的做法。例如:

while True:
    try:
        personsAge = int(input("<Enter your age>"))
        break
    except ValueError:
        print('Please input an integer.')
        continue

相关问题