def main():
selectionvalid = False
print("Welcome to virtue vending machine!")
print("Machine only takes $1 bills")
table()
while True:
user = input("Select your choice:")
if user == 'A1':
selectionvalid = True
print("Snickers: $.89")
change = bills() - a1
elif user == 'A2':
print("M&Ms: $1.39")
change = bills() - a2
selectionvalid = True
elif user == 'A3':
print("M&Ms: $1.39")
change = bills() - a2
selectionvalid = True
elif user == 'B1':
print("Lays: $.50")
change = bills() - a3
selectionvalid = True
elif user == 'B2':
print("Doritos: $.50")
change = bills() - a3
selectionvalid = True
elif user == 'B3':
print("Cheetos: $1.49")
change = bills() - a5
selectionvalid = True
elif user == 'C1':
print("TicTac: $1.04")
change = bills() - a6
selectionvalid = True
elif user == 'C2':
selectionvalid = True
print("Starburst: $.79")
change = bills() - a7
elif user == 'C3':
selectionvalid = True
print("Skittles: $2.49")
change = bills() - a8
else:
print("Item not available.")
print("Please, select your choice again:")
if selectionvalid == True:
print("Your change is:$", format(change, '.2f'))
message()
break
return selectionvalid
def bills():
totals = 0
bills = int(input("Insert your bills:$"))
while bills > 4:
print("Please, enter less than $4")
bills = int(input("Insert your bills:$"))
else:
print("You've inserted $",bills,"dollars")
return bills
def message():
print("Your,",,"is dispensed below!")
print("Thank you! Come Again!")
我试图让用户输入选择显示为def消息()是否有另一种方法可以将if-elif-else中的代码压缩成更像循环的东西?我听说过字典和列表,但我认为这似乎太复杂了。 例如: "你的窃笑'分配在" "你' Kitkat'分发在"
之下谢谢
答案 0 :(得分:1)
字典比你现有的字典更复杂?字典会清理你的很多代码并获得1/3的代码,主要是elif
s
vendingdict = {"A1": ["Snickers", 0.89],
"A2": ["M&Ms", 1.39],
"A3": ["Lays", 0.50]}
def main():
global myselection
while True:
myselection=input("Welcome to virtue vending machine!\nMachine only takes $1 bills\nSelect your choice:\n")
try:
if vendingdict[myselection] != None:
break
except KeyError:
print("\nPlease input valid selection\n")
continue
def bills():
while True:
try:
cashin = int(input("Insert your bills: $"))
except ValueError:
print("Please insert valid tender!")
continue
cashout = 0
if cashin>=vendingdict[myselection][1]:
cashout = cashin - vendingdict[myselection][1]
print("Your change is $%.2f" % cashout)
print("Your %s is below!" % vendingdict[myselection][0])
break
else:
print("Insufficient money, please insert more.")
print(cashin)
cashin = 0
continue
main()
bills()
答案 1 :(得分:0)
为什么不能将用户输入选择作为参数发送到message()
?也许创建一个字典products
,用户输入作为键,产品作为值。然后是message(products[userInput])
。