Python错误。无法将int对象转换为“str”imlicitly(完全困惑初学者在这里)

2024-09-27 18:06:47 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我决定做一个小的代码字符串,把你的年龄转换成狮子年(基本上把你的年龄乘以5)。 我的问题是我不能让它把年龄作为一个整数输入,或者我不能让它打印下面的“lionage”整数。你知道吗

代码和错误符号如下:

name = input ("please type your name in: ")
age = int(input ("please type your age in: "))
age = int(age)
five = int(str(5))
lionage = int(age*five)

print ("Hello " + name + "! Your age is " + age + " but in lion years it's " + str(lionage) + " years")

错误:无法将“int”对象隐式转换为str

我可能在代码中出错了。你知道吗

(顺便说一句,请优先给我一个为什么出错的答案,以及我如何修复它简化代码使之更小。(我想自己学,谢谢:))


Tags: 代码nameininputageyourtype错误
3条回答

Python可以打印数字,字符串。。。只要类型没有混淆,几乎什么都可以。在您的例子中,age是一个数字,要打印的行的其余部分是一个字符串。您需要通过添加str(age)而不是仅仅添加age来将数字转换为字符串。你知道吗

年龄是一个整数,您试图用字符串连接。在python中,不能直接这样做。你知道吗

print ("Your age is " + age)) # <- wrong answer

在合并之前必须将年龄转换为字符串

print ("Your age is " + str(age)) # <- Correct answer

在所有变量周围添加str()。你知道吗

例如:

a = 21
print("Your age is " + str(a))

这将输出“Hello World”(没有语音标记)。你知道吗

相关问题 更多 >

    热门问题