-3

我是 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
4

3 回答 3

3

错误准确地指出出了什么问题。改变这个:

print("your dog's age is " + (DogAge - 2 * 4 + 22))

对此:

print("your dog's age is " + str(DogAge - 2 * 4 + 22))

您不能将字符串对象与整数连接起来。

于 2013-02-09T13:44:45.437 回答
3

另一种解决方案:

print("your dog's age is {0}".format((DogAge - 2) * 4 + 22))

(假设您要计算(DogAge-2) * 4 + 22,而不是DogAge + 14)。

于 2013-02-09T13:48:10.310 回答
0

您可能需要考虑以不同的方式重新组织您的代码,以分离出狗年龄的计算和值的实际打印。

因为如果它变得更复杂,那么以后可以将该代码重构为一个函数。

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))
于 2013-02-09T14:06:28.593 回答