Python:添加结果变得不简单

时间:2019-05-10 06:14:17

标签: python python-3.7

在我的python代码中,除“总计”之外,所有结果都很好。不是给我变量的总和,而是给我字符串的总和?

age = '23'
height = '6.25' #feets
weight = '70' #kgs
eyes = 'hazel'
teeth = 'white'
hair = 'brown'

print(f"Lets talk about {name}." )
print(f"He's {height} feet tall.")
print(f"He's {weight} kilos heavy.")
print("Actually that's not too heavy.")
print(f"He's got {eyes} eyes and {hair} hairs.")
print(f"His teeth are usually {teeth} depending on the coffee.")


total = age + height + weight
print(f"If I add {age}, {height} and {weight}, I get {total}.")
PS E:\python programs> python p4.py
Lets talk about vishwjeet.
He's 6.25 feet tall.
He's 70 kilos heavy.
Actually that's not too heavy.
He's got hazel eyes and brown hairs.
His teeth are usually white depending on the coffee.
If I add 23, 6.25 and 70, I get 236.2570.

请看一下我的程序。See in image python program

结果

Result of program

2 个答案:

答案 0 :(得分:2)

所有变量均为字符串格式。因此,当您在最后添加它们时,它将变成串联,而不是预期的添加。要解决此问题,您可以:

# set all variables as int/floats from the start
age = 23
height = 6.25
wright = 70

或者您可以:

# cast them as int/floats before adding
total = int(age) + float(height) + int(weight)

答案 1 :(得分:0)

现在,您通过执行total = age + height + weight来连接字符串,因此得到total=236.2570.,因为'23'+'6.25'+70'='236.2570'

您需要将变量分别转换为int(年龄和体重)或float(身高),添加它们,然后您将获得正确的答案

name = 'vishwajeet'
age = '23'
height = '6.25' #feets
weight = '70' #kgs
eyes = 'hazel'
teeth = 'white'
hair = 'brown'

print(f'Lets talk about {name}.' )
print(f"He's {height} feet tall.")
print(f"He's {weight} kilos heavy.")
print("Actually that's not too heavy.")
print(f"He's got {eyes} eyes and {hair} hairs.")
print(f"His teeth are usually {teeth} depending on the coffee.")

#Convert age and weight to int and height to float, and add it
total = int(age)+ float(height) + int(weight)
print(f"If I add {age}, {height} and {weight}, I get {total}.")

现在输出为

Lets talk about vishwajeet.
He's 6.25 feet tall.
He's 70 kilos heavy.
Actually that's not too heavy.
He's got hazel eyes and brown hairs.
His teeth are usually white depending on the coffee.
If I add 23, 6.25 and 70, I get 99.25.

另一种选择是在开头将变量定义为intfloat而不是string

name = 'vishwajeet'

#Define variables as int or floats instead of string
age = 23
height = 6.25 #feets
weight = 70 #kgs

eyes = 'hazel'
teeth = 'white'
hair = 'brown'

print(f'Lets talk about {name}.' )
print(f"He's {height} feet tall.")
print(f"He's {weight} kilos heavy.")
print("Actually that's not too heavy.")
print(f"He's got {eyes} eyes and {hair} hairs.")
print(f"His teeth are usually {teeth} depending on the coffee.")

total = age+ height + weight
print(f"If I add {age}, {height} and {weight}, I get {total}.")

输出将与上面相同