我是python的极端初学者,我想知道这个程序我设置计算提示有什么问题
total = input("What is the bill total? ")
tperc = input("Would you like to give a 15% or 20% tip? ")
tip15 = total * .15
tip20 = total * .20
if tperc == "15":
print("\nThat would be a $" + tip15 + "tip.")
if tperc == "15%":
print("\nThat would be a $" + tip15 + "tip.")
if tperc == "20":
print("\nThat would be a $" + tip20 + "tip.")
if tperc == "20%":
print("\nThat would be a $" + tip20 + "tip.")
input("\nPress enter to exit.")
感谢您的帮助
答案 0 :(得分:3)
public IEnumerableSomeClassConverter : JsonConverter
{
public override bool CanConvert(Type objectType) {}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// Handle the weirdness here and return my IEnumerable
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {}
}
在Python 3.X中,total = input("What is the bill total? ")
#...
tip15 = total * .15
返回一个字符串。您不能将字符串乘以浮点数。
在进行任何算术之前将input
转换为数字。
total
或者,理想情况下,使用Decimal类型进行货币计算,因为浮点运算往往是not perfectly accurate。
total = float(input("What is the bill total? "))
from decimal import Decimal
total = Decimal(input("What is the bill total? "))
#...
tip15 = total * Decimal("0.15")
这也是一个问题,因为你不能连接字符串和float / Decimal。转换为字符串或使用字符串格式。后者可能更好,因为你可以舍入到小数点后两位。
print("\nThat would be a $" + tip15 + "tip.")