【发布时间】:2021-02-23 19:06:24
【问题描述】:
所以我在这里有一个小任务,我必须在其中获取用户输入,根据所述输入为变量分配不同的值,然后打印出它的总和。如果我在“if”中执行“if”,它会起作用,但一开始就会有这么多的文字。我正在尝试找到一种方法来读取用户输入并将其与某个值匹配。也许这与数据结构有关,但我还没有那么深入。有什么建议么? 代码如下:
input1 = input()
day = input()
quantity = float(input())
if input1 not in ["banana", "apple", "orange", "grapefruit", "kiwi", "pineapple", "grapes"]:
print("error")
if day in ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]:
banana = 2.50
apple = 1.20
orange = 0.85
grapefruit = 1.45
kiwi = 2.70
pineapple = 5.50
grapes = 3.85
elif day in ["Saturday", "Sunday"]:
banana = 2.70
apple = 1.25
orange = 0.90
grapefruit = 1.60
kiwi = 3
pineapple = 5.60
grapes = 4.20
else:
print("error")
price = input1 * quantity
print(f"{price}:.2f")
【问题讨论】:
-
这能回答你的问题吗? How do I create variable variables? 简而言之,使用字典而不是变量。作为奖励,您可以通过
if input1 not in d:来检查它是否无效。 -
like {'banana' : [price week , price week-end] , ..........}
-
input1 = input() week = input() how = input() col = int dict ={'banana' : [1 , 2]} if week == 'a': col = 0 if week == 'b': col = 1 print(int(dict[input1][col])*int(how))
标签: python string variables input