如何让这段代码在保持函数内的数字的情况下运行?

huangapple go评论94阅读模式
英文:

How can I make this code work while keeping the numbers inside the function?

问题

  1. 我希望函数能够完成大部分工作根据项目的要求
  1. def tax(choice):
  2. a = 1.4
  3. b = 2.2
  4. print(choice * 1.12)
  5. print("你要买什么?")
  6. print("[a] 盐 - $1.40")
  7. print("[b] 胡椒 -$2.20")
  8. choice = input()
  9. print("它将花费 ${}".format(tax(choice)))

我已尽力根据您的要求进行翻译,不包含代码部分。

英文:

I want the function do most of the work, due to the requirements of the project

  1. def tax(choice):
  2. a = 1.4
  3. b = 2.2
  4. print(choice * 1.12)
  5. print("What will you buy?")
  6. print("[a] Salt - $1.40")
  7. print("[b] Pepper -$2.20")
  8. choice = input()
  9. print("It will cost ${}".format(tax(choice)))

I have tried everything to my knowledge (which isn't a lot)

答案1

得分: 3

你可以使用字典来从 (string) 输入中获取选择:

  1. def tax(choice):
  2. choices = {"a": 1.4, "b": 2.2}
  3. return choices[choice] * 1.12
  4. print("你要买什么?")
  5. print("[a] 盐 - $1.40")
  6. print("[b] 胡椒 - $2.20")
  7. choice = input()
  8. print("它将花费 {}".format(tax(choice)))

你可能还想使用 f-strings,因为这是包含变量的消息的现代打印方式:

  1. print(f"它将花费 {tax(choice)}.")

(注意在开头的 f)

英文:

You can use a dictionary to get the choice from the (string) input:

  1. def tax(choice):
  2. choices = {"a" : 1.4, "b" : 2.2}
  3. return choices[choice] * 1.12
  4. print("What will you buy?")
  5. print("[a] Salt - $1.40")
  6. print("[b] Pepper -$2.20")
  7. choice = input()
  8. 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:

  1. print(f"It will cost {tax(choice)}.")

(note the f at the beginning)

huangapple
  • 本文由 发表于 2023年2月9日 03:32:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75390857.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定