可变小费计算器输入

2024-10-03 13:31:09 发布

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

我正在尝试创建一个小费计算器像其他新手一样,当然我遇到了一个问题。大多数代码都可以正常工作,但我不知道如何将用户输入的提示信息合并到总计中。你知道吗

这个页面是一个很好的资源,它告诉我需要将python指向将输入解释为解决方案中使用的数学的方向。不过,我没能在脑子里把它翻译成我的代码。你知道吗

Tip Calculator Function

# Tip Calculator
import random
bill = input("How much was your bill? ")
x = float(bill)
tip10 = x * .10
tip15 = x * .15

tip20 = x * .20

tip10 = float(tip10)
tip15 = float(tip15)
tip20 = float(tip20)

total = x + tip10
total = x + tip15
total = x + tip20
print(f"If you would like to leave a 10%, the tip amount will be ${tip10}.")
print(f"If you would like to leave a 15%, the tip amount will be ${tip15}.")
print(f"If you would like to leave a 20%, the tip amount will be ${tip20}.")
input("How much tip would you like to leave? ")
print(f"Your total is ${total:.2f}.)

当我运行这个程序时,它只会在询问要留下多少小费后给我tip20结果,我最终发现这是因为它是总数的最后一行。你知道吗

如何将用户输入合并到最后一行代码的总计中?你知道吗


Tags: to代码youiffloatliketotalprint
3条回答

没有必要对每个提示都进行硬编码。你知道吗

# Tip Calculator
import random
bill = input("How much was your bill? ")
x = float(bill)
example_tips = [10, 15, 20]

for tip in example_tips:
    print(f"If you would like to leave a {tip}%, the tip amount will be ${x*tip/100}}.")
choice = input("How much tip would you like to leave? ")
total = x*(1+float(choice)/100)
print(f"Your total is ${total:.2f}.)

这里,choice是一个百分比,如example_tips。你知道吗

再次要求用户输入,然后根据他们所说的计算total。你知道吗

tipAmount = input("How much tip would you like to leave? (10, 15, 20) ")
if tipAmount == "10":
    total = x + tip10
elif tipAmount == "15":
    total = x + tip15
elif tipAmount == "20":
    total = x + tip20
else:
    total = x
    print("You're not leaving a tip? You cheapskate.")
print(f"Your total is ${total:.2f}")

我将把确保用户输入是这三个选项之一的问题留给读者作为练习(如果您陷入困境,请查看this answer)。你知道吗

input("How much tip would you like to leave? ")不输出到变量。你知道吗

而且,total = x + tip20是唯一对total有影响的语句。您要做的是将用户输入添加到变量中,方法是将此:input("How much tip would you like to leave? ")更改为:total = x + float(input("How much tip would you like to leave? "))

当然,如果您希望输出的提示对用户来说是一种建议的话。如果你想让用户使用你的值,你最好使用绿斗篷人的答案。你知道吗

相关问题 更多 >