I have a doubt. Previously I made my first Python program with everything I learned, it was about the system of a vending machine, but one of the main problems was that it was too redundant when conditioning and ended up lengthening the code. So they explained to me that I should define the functions and return in case they are not fulfilled.
But my question is, how can I call the value of a variable, specifically a number, by conditioning it?
Example:
# -*- coding: utf-8 -*-
def select_ware(wares):
print(' '.join(wares))
while True:
selected = input("Elige un código: ")
if selected in wares:
print(f'El precio es de: {wares[selected]}\n')
break
else:
print("El código no existe, introduce un código válido")
return selected
def pay_ware(wares, selected):
money_needed = wares[selected]
money_paid = 0
while money_paid < money_needed:
while True:
try:
money_current = float(input("Introduce tu moneda: "))
break
except ValueError:
print('Please enter a number.')
money_paid += money_current
print(f'Paid ${money_paid}/${money_needed}')
if money_paid>{select_ware}: #This is the part where I want to substitute the value to call the variable.
print(f'Su cambio es ${money_paid-money_needed}')
return money_paid, money_needed
def main():
wares = {'A1': 6, 'A2': 7.5, 'A3': 8, 'A4': 10, 'A5': 11}
selected_ware = select_ware(wares)
pay_ware(wares, selected_ware)
if __name__ == "__main__":
main()
The question is this:
if money_paid>{select_ware}: #This is the part where I want to substitute the value to call the variable.
print(f'Su cambio es ${money_paid-money_needed}')
How can I implement it to avoid making long conditions for each value, that is, for the value of 'A1': 6, 'A2': 7.5, 'A3': 8, 'A4': 10, 'A5': 11
?
Thanks for reading. Regards.
You are almost done! Just modify {select where} by money needed. You can also modify the Try Exception statement in order to avoid stop your program until the money current is a float number:
def pay_ware(wares, selected):
money_needed = wares[selected]
money_paid = 0
valid_money_current = False # para chequear que el pago sea con monedas
while money_paid < money_needed:
while not valid_money_current:
money_current = float(input("Introduce tu dinero: "))
if type(money_current) is float:
valid_money_current = True # el pago es valido
else:
print('Please enter a number.')
money_paid += money_current
print(f'Paid ${money_paid}/${money_needed}')
if money_paid > money_needed: #This is the part where I want to substitute the value to call the variable.
print(f'Su cambio es ${money_paid-money_needed}')
return money_paid, money_needed