Python TypeError:创建年龄转换器时-:'str'和'int'的操作数类型不受支持?
有人知道为什么这行不通吗?单击链接以查看打印屏幕 如果你能帮我修一下,我会特别感激的 提前感谢, Ben Johnson输入返回一个字符串。字符串不能等于整数。如果PetAge==1是错误的,那么其他部分也是错误的,因为不能使用字符串进行计算。你必须写作Python TypeError:创建年龄转换器时-:'str'和'int'的操作数类型不受支持?,python,math,converter,Python,Math,Converter,有人知道为什么这行不通吗?单击链接以查看打印屏幕 如果你能帮我修一下,我会特别感激的 提前感谢, Ben Johnson输入返回一个字符串。字符串不能等于整数。如果PetAge==1是错误的,那么其他部分也是错误的,因为不能使用字符串进行计算。你必须写作 PetAge= int(input("blabla")) 在这里你的程序应该是怎样的 if pet=="cat": PetAge=int(input("Enter your cat age")) if PetAge==1:
PetAge= int(input("blabla"))
在这里你的程序应该是怎样的
if pet=="cat":
PetAge=int(input("Enter your cat age"))
if PetAge==1:
print ("blabla")
elif PetAge==2:
print ("morebla")
else:
CatAge=(PetAge-2)+25+4
print ("Your cat is {} cat years old".format(CatAge))
还记得
"26" != 26
这应该会给你一些关于如何将你的程序划分成函数的想法,使它更容易思考
def get_int(prompt):
"""
Prompt user to input an integer value
Loop until a good value is entered,
then return the value
"""
while True:
try:
return int(input(prompt))
except ValueError:
# couldn't convert to int - try again
pass
def cat_age(age):
"""
Convert human years to cat years
"""
if age == 1:
return 15
elif age == 2:
return 25
else:
return 25 + (age - 2) * 4
# A more advanced technique:
# a function that creates a function!
def make_age_function(given_ages, rate):
num = len(given_ages)
last = given_ages[-1] if num else 0
def age_function(age):
"""
Given an age in years, calculate human-equivalent age
"""
if age < num:
return given_ages[age - 1]
else:
return last + (age - num) * rate
return age_function
# Now let's use it to make a dog_age function:
dog_age = make_age_function([15, 25], 4)
# dog_age gives exactly the same results as cat_age
# How about a turtle_age function?
turtle_age = make_age_function([], 0.45)
# We need to keep track of which pets
# we know how to convert ages for
known_pets = {
"cat": cat_age,
"dog": dog_age,
"turtle": turtle_age
}
def main():
print("Welcome to the Pet Age Converter")
while True:
print("What kind of pet do you have? (or hit Enter to exit)")
pet = input().strip().lower()
if pet in known_pets:
age = get_int("What is your {}'s age? ".format(pet))
# look up the appropriate age converter function
age_fn = known_pets[pet]
# and use it to calculate pet age
pet_age = age_fn(age)
# now show the results
print("Your {} is {} {} years old.".format(pet, pet_age, pet))
elif pet:
print("I didn't know anyone had a {}!".format(pet))
else:
# exit the while loop
break
if __name__ == "__main__":
main()
一般来说,尝试将代码示例内联到有关StackOverflow的问题中。也许你可以在这个网站上找到你认为最相关的部分,并保留一个指向完整源代码的链接。我想这在Python2.7中也会起到预期的作用,但是你使用的是Python3.x。。。看见