我是python的新手,但我试图将DogAge放入数学方程中,但仍然无法使用
Animal = input("dog or cat? ")
if Animal == "dog":
DogAge = int(input("how old is you dog? "))
else:
CatAge = int(input("how old is your cat? "))
if DogAge == 1:
print("your dog's age is 11")
elif DogAge == 2:
print("your dog's age is 22")
else:
print("your dog's age is " + (DogAge - 2 * 4 + 22))
提供:
TypeError:无法将"int"对象隐式转换为str
错误准确地指出了问题所在。更改此项:
print("your dog's age is " + (DogAge - 2 * 4 + 22))
对此:
print("your dog's age is " + str(DogAge - 2 * 4 + 22))
不能将字符串对象与整数连接。
另一个解决方案:
print("your dog's age is {0}".format((DogAge - 2) * 4 + 22))
(假设要计算(DogAge-2) * 4 + 22
,而不是DogAge + 14
)。
您可能需要考虑以不同的方式重新组织代码,以将dogs age的计算和值的实际打印分开。
如果以后变得更复杂,那么可以将代码重构为函数。
Animal = input("dog or cat? ")
if Animal == "dog":
DogAge = int(input("how old is you dog? "))
else:
CatAge = int(input("how old is your cat? "))
if DogAge == 1:
calculated_dogs_age = 11
elif DogAge == 2:
calculated_dogs_age = 22
else:
calculated_dogs_age = DogAge - 2 * 4 + 22
print("your dog's age is {0:d}".format(calculated_dogs_age))