尽管使用str / int仍无法打印数字

时间:2019-08-19 04:10:41

标签: python-3.x

我是一个试图学习python 3的菜鸟,我试图将half_age包含为一个字符串,而没有直接使用数字9作为字符串,但是我无法弄清楚。

我尝试过:

print = str(18//2)
print = int(18//2)
print = float(18/2)

my_age = 18
half_age = (18//2)
name = "Kenny!"
greeting = "Kia Ora, "

print(greeting + name)

print("Your age is " + my_age + "and half your age is " + str(half_age ))
print("Your age is " + my_age + "and half your age is " + str(half_age ))
TypeError: can only concatenate str (not "int") to str

2 个答案:

答案 0 :(得分:1)

尝试使用str格式化所有数字,即。

my_age = 18
half_age = (18//2)
name = "Kenny!"
greeting = "Kia Ora, "

print(greeting + name)

print("Your age is " + str(my_age) + " and half your age is " + str(half_age))

答案 1 :(得分:1)

只需使用现代的f-strings

my_age = 18
half_age = (18//2)
name = "Kenny"
greeting = "Kia Ora"


print(f'{greeting}, {name}!')
print(f"Your age is {my_age} and half your age is {half_age}")

print(f"Your age is {my_age} and half your age is {my_age/2}")