我是最近才开始学习编码的,这是我的第一个问题,如果这个问题太愚蠢,请原谅我。
我像昨天一样开始学习Python,但我陷入了这个问题,在执行if
语句时,我收到一条错误消息,指出{{1}的实例之间不支持>
}和str
。
我了解一些JavaScript,并且我认为变量int
被视为字符串,但是如果输入为数字,则不应将其视为整数。
我应该在此处进行哪些更改,以使其按预期的方式工作。
age
我希望程序根据输入的年龄打印相应的语句,但是在name = input("Enter your name:")
print("Hello, " +name)
age = input("Please enter your age:")
if age > 3:
print("You are allowed to use the internet.")
elif age <= 3:
print("You are still a kid what are you doing here.")
语句的开头出现错误,指出无法使用if
运算符进行比较一个字符串和一个整数。
答案 0 :(得分:0)
您需要将年龄转换为int
,默认为string
name = input("Enter your name:")
print("Hello, " +name)
age = int(input("Please enter your age:"))
if age > 3:
print("You are allowed to use the internet.")
elif age <= 3:
print("You are still a kid what are you doing here.")
答案 1 :(得分:0)
正如回溯所说,age
是一个字符串,因为它刚被用户“输入”。与C不同,没有方法可以执行类似scanf("%d", &age)
的操作,因此您需要使用age = int(age)
手动将age转换为整数。
name = input("Enter your name:")
print("Hello, " +name)
age = input("Please enter your age:")
# do exception handling to make sure age is in integer format
age = int(age)
答案 2 :(得分:0)
比较运算符正在将字符串与整数进行比较。因此,在比较之前将您的字符串转换为int
name = input("Enter your name:")
print("Hello, " +name)
age = input("Please enter your age:")
if int(age) > 3:
print("You are allowed to use the internet.")
elif int(age) <= 3:
print("You are still a kid what are you doing here.")