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
Related
I am trying to make a simple code to input a positive integer in the most accurate way possible. I mention that I am very new to the language.
Here is my code :
while number != None:
try:
while True:
number = int(input("Donnez la longueur de votre liste: "))
if number > 0:
break
except TypeError:
print("Tu doit donner un nombre entier")
The warning I get is number can be Undefined I am not aware of what is the specific situation where number is undefined as the while loop breaks only when number is not None ( means defined according to me ). I’m so grateful for your help. It is a challenging time but you would make it easier.
You can sidestep any warnings with a more idiomatic loop:
while True:
number = input("Donnez la longueur de votre liste: ")
try:
number = int(number)
except ValueError:
print("Tu doit donner un nombre entier")
continue
if number > 0:
break
I am writing a program that has multiple options to modify a dictionary in python. The user has four options, and after completing an option I want the program to bring back the user to the main menu.
So far, every option works correctly except it doesn't bring the user back to the main menu, and instead loops for ever
user_input = int(input("Faites un choix..."))
liste_epicerie = {}
while True:
if user_input == 1:
print(liste_epicerie)
if liste_epicerie == {}:
print("La liste est vide")
continue
So this code should bring back the user to user_input, but instead prints "La liste est vide" for ever.
What am I doing wrong?
You have to actually read the user input again (inside the loop):
liste_epicerie = {}
while True:
user_input = int(input("Faites un choix..."))
if user_input == 1:
# ...
elif ...:
# ...
# under some condition
break
The variable user_input does not magically remember and repeat how its value came to be.
sum=0
count=0
while True:
n=input ("enter the value :")
if n=="exit":
break
try:
float(n)
except:
print ("enter the numeric value")
continue
sum=sum+n
count=count+1
print(sum,count,sum/count)
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
Just grabbed a calculator with python integrated (numworks).
I'm writing a python program wich includes a function to check if an input is a number (float).
When i type a proper float number everything goes right, but when an exception is catched here is the behavior:
the except block is run properly
then the while loops restarts, ask my imput again and enter an infite loops and freezes. No time for typing my input again.
I'm not familiar with Python, I'm pretty sure it's a simple syntax thing... But I didn't manage to work it out.
Help would be appreciated!
Here is the code:
# controle de saisie d'un nombre
def inputFloat(text):
ret = ''
while ret is not float:
try:
ret = float(input(text + " (nombre)"))
except ValueError:
print("saisie incorrecte.")
return ret
# test
def test():
print(inputFloat("saisir nombre"))
# affichage du menu
while True:
print("[1] test")
print("[0] quitter")
choix = input("Choisir une fonction:")
if choix == "0":
print("au revoir.")
break
elif choix == "1":
test()
Cheers
PS: infos about the environnement : the calculator uses MicroPython 1.9.4 (source https://www.numworks.com/resources/manual/python/)
Edit
here is the clean working version of the code with all suggestions from you guys.
Pushed it to the calc: works like a charm.
# controle de saisie d'un nombre
def inputFloat(text):
while True:
try:
return float(input(text + " (nombre)"))
except ValueError:
print("saisie incorrecte.")
continue
# test
def test():
print(inputFloat("saisir nombre"))
# affichage du menu
while True:
print("[1] test")
print("[0] quitter")
choix = input("Choisir une fonction:")
if choix == "0":
print("au revoir.")
break
elif choix == "1":
test()
break
I think the simplest way is the following:
def input_float():
while True:
try:
return float(input("Give us a number: "))
except:
print("This is not a number.")
You could also use a recursive version:
def input_float():
try:
return float(input("Give us a number: "))
except:
print("This is not a number.")
return input_float()
currently im trying to solve a problem in the code i wrote, for some reason whenever i call imprimir() it only shows the last added person while it should show all the persons added.
libro = {}
def agregar(rut, nombre, edad):
estudiante = {}
estudiante['rut'] = rut
estudiante['nombre'] = nombre
estudiante['edad'] = edad
libro['rut'] = estudiante
def imprimir():
for rut in libro:
estudiante = libro[rut]
print(estudiante['rut'], estudiante['nombre'], estudiante['edad'])
def main():
contador = 0
while contador < 2:
rut = input("rut: ")
nombre = input("nombre: ")
edad = input("Edad: ")
contador = contador + 1
agregar(rut, nombre, edad)
imprimir()
main()
I had the code limited to only 2 people to be added. so if for the first person i write, rut = 1, nombre = 1 and edad = 1, and for the second, rut = 2, nombre = 2 and edad = 2. While using main(), it should print:
1 1 1
2 2 2
but instead it just prints 2 2 2 with 1 1 1 not found, my guess is that somehow the added person are not added but instead rewritten, but i cant find why, if i includo imprimir() inside the while in the main() it prints each person as soon as i finish adding one, but the idea its that the program should print all the added people once i finish adding them.
The problem is your adding the items with the same key so the dict just overrides the last value with each entry you add...
libro = {}
def agregar(rut, nombre, edad):
estudiante = {}
estudiante['rut'] = rut
estudiante['nombre'] = nombre
estudiante['edad'] = edad
# this would override the previous entry since it's always the same key
libro['rut'] = estudiante
# use a key that is unique and all entries will be preserved
libro[rut] = estudiante
# or for some truly unique keys
libro[str(uuid.uuid4())] = estudiante
Need to program a CPU that decides between throwing the dice again or ending its turn.
The game already works with two players. Now I just need the 2nd player to make decisions on its own.
What do I do? This is a part of the code:
while not juego_termina:
print("")
jug_turno.lanzar_dado(dado)
jug2.dec_cpu()
while jug_turno.jugando:
jug2.dec_cpu() #Se anida un while para cada turno del jugador
print("Puntaje parcial acumulado:",end=' ')
print(jug_turno.p_parcial)
continuar = ""
jug2.dec_cpu()
while continuar != "SI" and continuar != "NO": #Pregunta si continua el turno
print("Desea seguir jugando? (SI/NO)")
continuar = input().upper() #.upper para la mayuscula
if continuar == "SI":
jug_turno.lanzar_dado(dado)
else:
jug_turno.terminar_turno()
if jug_turno.p_total >= meta: #Compara el puntaje total con la meta asignada al inicio
juego_termina = True #Se acaba el juego y salta a nombrar el ganador
else:
if jug_turno == jug1:
jug_turno = jug2
else:
jug_turno = jug1
mostrar_puntajes(jug1,jug2)
print("El ganador es:")
print(jug_turno.nombre)
I only know a small amount of Spanish, so it's possible I'm reading your code incorrectly, but it looks like the game works like Blackjack - the winning player is the player who has the highest total without going over some maximum value (21 in the case of Blackjack). The code for the simplest algorithm you could use probably looks something like this:
def dec_cpu(maximum):
total = 0
while total < maximum and (highest_possible_die_roll / 2) < (maximum - total):
total = total + roll_die()
return total
The (highest_possible_die_roll / 2) < (maximum - total) part is essentially saying, "if there's less than a 50% chance that rolling the die again will put me over the maximum, roll again". From there, you can refine it depending on the rules of the game. For example, if there's an amount of money being wagered each time, the computer might want to be 75% sure that they won't go over the maximum when the die is rolled if there's a lot of money on the line.