Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
获取字符串输入,尝试将其分配给/Python之后的变量_Python_String_Variables_Input - Fatal编程技术网

获取字符串输入,尝试将其分配给/Python之后的变量

获取字符串输入,尝试将其分配给/Python之后的变量,python,string,variables,input,Python,String,Variables,Input,所以我这里有一个小任务,我必须得到用户的输入,根据所说的输入给变量分配不同的值,然后打印出它的总和。如果我在“如果”中做“如果”,它会起作用,但那将是如此多的文本开始。我试图找到一种方法来读取用户输入并将其与某个值匹配。也许这与数据结构有关,但我还不太了解。有什么建议吗? 代码如下: input1 = input() day = input() quantity = float(input()) if input1 not in ["banana", "apple

所以我这里有一个小任务,我必须得到用户的输入,根据所说的输入给变量分配不同的值,然后打印出它的总和。如果我在“如果”中做“如果”,它会起作用,但那将是如此多的文本开始。我试图找到一种方法来读取用户输入并将其与某个值匹配。也许这与数据结构有关,但我还不太了解。有什么建议吗? 代码如下:

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")

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

工作日=[“周一”、“周二”、“周三”、“周四”、“周五”]
周末=[‘周六’、‘周日’]
水果价格={
香蕉:{'weekday':2.5,'weekend':2.5},
苹果:{'weekday':1.2,'weekend':1.25},
#……休息
}
def get_价格(水果、日期、数量):
如果水果不在水果价格中:
raise VALUERROR(f'没有这样的结果:{FROUT}')
如果一天不在工作日,一天不在周末:
raise VALUERROR(f'无此日期:{day}')
价格=水果价格[水果][“工作日”如为工作日,则为“周末”]
退货价格*数量
_水果=输入().strip()
_天=输入().strip()条
_数量=浮动(输入().strip())
尝试:
打印(获取价格(\u水果、\u天、\u数量))
除ValueError作为错误外:
打印(f'error:{str(err)}')

这是否回答了您的问题?简而言之,使用dict而不是变量。作为奖励,如果input1不在d:中,您可以执行
来检查它是否无效。例如{'banana':[price week,price week end],…..}input1=input()week=input()how=input()col=int dict={'banana':[1,2]}如果week='a':col=0如果week='b':col=1打印(int(dict[input1][col int])*int(how))