如何具有与用户输入不同的结果(下一个问题将第一个问题用户输入考虑在内以进行计算)


#Elecricity Plan
#these are the electricity plans
eplan = input('Enter your electricity plan (EFIR or EFLR): ')
if eplan.lower() == 'efir':
print('Thank you for choosing EFIR' )
elif eplan.lower() == 'eflr':
print('Thank you for choosing EFLR')
else:
print('Please enter your electricity plan in abbreviation')

用电量

我正在努力做到,当人们输入他们对电力
计划的答案时,它会在下一个问题中根据他们选择的是EFIR还是EFLR进行不同的计算(对他们的在考虑了用电量和他们在最后一个问题(

kwha = int(input('Enter the amount of electricity you used in month ')) 

只需根据第一个输入进行两种类型的计算,因为您已经将其存储在eplan变量中:

kwha = int(input('Enter the amount of electricity you used in month ')) 
if eplan.lower() == 'efir':
#do calculation
elif eplan.lower() == 'eflr':
#do another calculation

您可以考虑通过交换输入订单来使用类似的match/case,即先询问使用量,然后询问计划类型:

amount = float(input('Enter the amount of electricity used: '))
match input('Enter your electricity plan (EFIR or EFLR): '):
case 'EFIR':
pass # do EFIR calculations here
case 'EFLR':
pass # do EFLR calculations here
case _:
print('Unknown plan type')

您可以为不同的用户输入创建不同的函数。但这不是必要的,你可以使用if块,就像你做的那样!

def func_one():
print('Thank you for choosing EFIR')
# ...
def func_two():
print('Thank you for choosing EFLR')
# ...

然后做这样的事情:

if eplan.lower() == 'efir':
func_one()
elif eplan.lower() == 'eflr':
func_two()
else:
print('Please enter your electricity plan in abbreviation')

提示:您可以为类似的情况创建哈希图

map = {'efir': func_one, 'eflr': func_two}
if eplan.lower() in map:
map[eplan.lower()]()
else:
print('Please enter your electricity plan in abbreviation')

您也可以使用匹配

非常简单。您可以将代码直接放入条件块中,也可以将其分离为函数

if some_condition_is_true:
# do calculation or call another function
elif ...
else ...

最新更新