我正在通过一本《学习Python的艰难方法3》学习python。
我完全按照作者的要求去做,但是得到了不同的价值。以下是问题的摘要部分。我目前正在旅途中,所以没有这本书,但这是出于记忆,因为我昨晚尝试了100次。
age = '35'
height = '74'
weight = '180'
total = {age} + {height} + {weight}
print(f"If I add my {age}, {height} and {weight}, I get {total}.")
作者说我应该得到289。但是,我仍然得到3574180。我已经重新输入,反复验证,仍然得到年龄,身高和体重的字符串3574180与所有三个289的总和。我是莫名其妙,并希望得到任何反馈。提前非常感谢您。
答案 0 :(得分:2)
您要添加字符串,因此结果是年龄,体重和身高的串联。而是:
total = int(age) + int(height) + int(weight)
这会将值转换为int
,可以将它们加在一起
答案 1 :(得分:0)
好友发生的事情是您输入的年龄,身高和体重是一个字符串'' 所以总共会发生
total = '35' + '74' + '180'
他们只是合并在一起,而不是这里的计算
要计算字符串,必须将其转换为整数或浮点数
total = int(age) + int(height) + int(weight)
这将执行数学计算,您的代码将正常运行
答案 2 :(得分:0)
在解决了逻辑错误之后,我相信正确的程序代码如下。我已经对其进行了几次测试,并据此计算出收益。
barsInACase = 12
costPerCase = 8.00
costPerSingleBar = 1.00
#asks for the user to enter the number of bars they sold
sold = int (input ("How many candy bars did you sale? "))
#calculates the number of cases sold based off of the users input
casesSold = sold / barsInACase
#calculates the net earnings using the users input
netEarnings = (sold * costPerSingleBar) - (casesSold * costPerCase)
#displays the net earnings
print ("Your net earnings are $",
format (netEarnings, ',.2f'), ".", sep="")
#calculates the amount that the SGA gets
studentGovernmentAssociation = netEarnings * 0.10
#calculates the amount that the cheer team gets
cheerTeamsProceed = netEarnings - studentGovernmentAssociation
#displays the amount that the SGA gets
print ('The student government associations earnings are: $',
format (studentGovernmentAssociation, ',.2f'), ".", sep="")
#displays the amount that the cheer team gets
print('The cheer teams earnings are: $',
format (cheerTeamsProceed, ',.2f'), ".", sep="")
#displays a congratulatory message if the cheer team gets more than $500
if (cheerTeamsProceed >= 500):
print ("Congratulations! You have raised $500 or more!")
#displays a sorry message if the cheer team gets less than $500
else:
print ("Sorry! You did not meet your goal! ")