类型错误>=在“str”和“int”的实例之间不受支持

2024-10-01 15:41:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经写出了我的代码,但是我一直在if personsAge >= 1上收到一条错误消息。在

错误如下:

type error >= not supported between instances of 'str' and '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

Tags: andtheto代码agedataifis
1条回答
网友
1楼 · 发布于 2024-10-01 15:41:32

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

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

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

然后你就可以把它和其他整数比较了。在

每次将personsAge与字符串连接时,不要忘了将personsAge整数转换为带有str()的字符串。示例:

^{pr2}$

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

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

相关问题 更多 >

    热门问题