英文:
How can I make this code work while keeping the numbers inside the function?
问题
我希望函数能够完成大部分工作,根据项目的要求
def tax(choice):
a = 1.4
b = 2.2
print(choice * 1.12)
print("你要买什么?")
print("[a] 盐 - $1.40")
print("[b] 胡椒 -$2.20")
choice = input()
print("它将花费 ${}".format(tax(choice)))
我已尽力根据您的要求进行翻译,不包含代码部分。
英文:
I want the function do most of the work, due to the requirements of the project
def tax(choice):
a = 1.4
b = 2.2
print(choice * 1.12)
print("What will you buy?")
print("[a] Salt - $1.40")
print("[b] Pepper -$2.20")
choice = input()
print("It will cost ${}".format(tax(choice)))
I have tried everything to my knowledge (which isn't a lot)
答案1
得分: 3
你可以使用字典来从 (string
) 输入中获取选择:
def tax(choice):
choices = {"a": 1.4, "b": 2.2}
return choices[choice] * 1.12
print("你要买什么?")
print("[a] 盐 - $1.40")
print("[b] 胡椒 - $2.20")
choice = input()
print("它将花费 {}".format(tax(choice)))
你可能还想使用 f-strings,因为这是包含变量的消息的现代打印方式:
print(f"它将花费 {tax(choice)}.")
(注意在开头的 f
)
英文:
You can use a dictionary to get the choice from the (string
) input:
def tax(choice):
choices = {"a" : 1.4, "b" : 2.2}
return choices[choice] * 1.12
print("What will you buy?")
print("[a] Salt - $1.40")
print("[b] Pepper -$2.20")
choice = input()
print("It will cost {}".format(tax(choice)))
You may want to use f-strings too, as this is the modern way to print messages containing variables:
print(f"It will cost {tax(choice)}.")
(note the f
at the beginning)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论