【问题标题】:Getting string input, trying to assign it to a variable after / Python获取字符串输入,尝试将其分配给 / Python 之后的变量
【发布时间】: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


【解决方案1】:

正如 cmets 中所建议的,我会使用字典来处理这种情况,并且也会使用例外来处理水果名称/日期名称与预期不匹配的情况。例如:

weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
weekends = ['Saturday', 'Sunday']

fruit_prices = {
    'banana': {'weekday': 2.5, 'weekend': 2.5},
    'apple': {'weekday': 1.2, 'weekend': 1.25},
    # ...rest
}

def get_price(fruit, day, quantity):
    if fruit not in fruit_prices:
        raise ValueError(f'no such fruit: {fruit}')
    if day not in weekdays and day not in weekends:
        raise ValueError(f'no such day: {day}')

    price = fruit_prices[fruit]['weekday' if day in weekdays else 'weekend']
    return price * quantity

_fruit = input().strip()
_day = input().strip()
_quantity = float(input().strip())

try:
    print(get_price(_fruit, _day, _quantity))
except ValueError as err:
    print(f'error: {str(err)}')

【讨论】:

    猜你喜欢
    • 2020-06-10
    • 1970-01-01
    • 2022-10-17
    • 2015-05-04
    • 2022-01-14
    • 2020-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多