Python 类型错误:Can';t转换为';int';对象到数学方程中的str隐式变量

Python 类型错误:Can';t转换为';int';对象到数学方程中的str隐式变量,python,int,Python,Int,我对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") el

我对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: Can't convert 'int' object to str implicitly 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 >。

< P>你可能想考虑不同地重新组织你的代码,以分离出狗年龄的计算和实际的打印值。 如果代码变得更复杂,那么以后可以将其重构为函数

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))

@RachelGallen这与html或单选按钮无关。您是否知道
DogAge-2*4+22
不是
(DogAge-2)*4+22
,而是
DogAge+14
?…因为它被计算为
DogAge-(2*4)+22
,因为默认情况下,乘法比加法和减法具有更高的运算符优先级,除非它被括号覆盖。天哪,我不会对OPs代码做太多更改,所以它们无法识别它。这是一个很好的平衡,很难知道何时停止。您只需查看OP代码的格式,使其感觉不舒服。谢谢,这有助于很多人,更简单地说,您还可以使用
打印(“您的狗的年龄是”,DogAge-2*4+22)