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

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

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)

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:

确定