ValueError: invalid literal for int() with base 10: 'one' [duplicate] - python

This question already has answers here:
Loop until a specific user input [duplicate]
(2 answers)
Closed 3 years ago.
def admin():
def admin_try():
print ("1) Ver lista de productos.",'\n')
print ("2) Agregar un producto.",'\n')
print ("3) Modificar un producto (Precio).",'\n')
print ("4) Eliminar un producto.",'\n')
print ("5) Pedidos agendados.",'\n')
print ("6) Salir.",'\n')
global opcion
opcion = int(input("Indique una opción valida: "))
while True:
try:
admin_try()
except (ValueError):
print ("La instrución debe ser numerica.")
admin_try()
admin() # I get an error
I get an error when executing this code and I want to cycle with try,
and I get this error at the time of executing the code. What I want is that whenever the user puts that wrong, the function is always executed.
Traceback (most recent call last):
File "g:/proyecto/try.py", line 15, in admin
admin_try()
File "g:/proyecto/try.py", line 11, in admin_try
opcion = int(input("Indique una opción valida: "))
ValueError: invalid literal for int() with base 10: 'uno'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "g:/proyecto/try.py", line 20, in <module>
admin()
File "g:/proyecto/try.py", line 18, in admin
admin_try()
File "g:/proyecto/try.py", line 11, in admin_try
opcion = int(input("Indique una opción valida: "))
ValueError: invalid literal for int() with base 10: 'one'

Don't use try-except:
The need to use try-except arises from converting the input to an int
If you try to convert a non-numeric input to int, a ValueError exception will occur
This code can be executed without converting to an int
Use the membership operator, in to determine if the input is in the list of accepted inputs. If the input is not in the list, admin() is called again.
Setting opcion as a global variable is not required.
If it's required outside of admin(), use return.
If opcion is required as an int outside of the admin() function, then use return int(opcion)
def admin():
print ("1) Ver lista de productos.",'\n')
print ("2) Agregar un producto.",'\n')
print ("3) Modificar un producto (Precio).",'\n')
print ("4) Eliminar un producto.",'\n')
print ("5) Pedidos agendados.",'\n')
print ("6) Salir.",'\n')
opcion = input("Indique una opción valida: ")
while True:
if opcion in ['1', '2', '3', '4', '5', '6']:
return opcion # return the value if it's needed outside of admin()
break # stops the loop because a correct option has been selected
else:
print ("La instrución debe ser numerica.\n")
admin()
admin()

Related

How to avoid "can be undefined" error in Python?

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

How to condition a variable by calling the value?

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

Python while loops never ends (on a numworks calculator) [duplicate]

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

Python file executable error

I did a fuel calculator program for a game with python and then I compiled to .exe with cx_Freeze. It converts it well to .exe and I can open the executable but when the script interacts with the user the window closes after pressing enter when the user introduce the requested information.
This is one part of the code, after requesting some information to the user the program does some calculations but I think it's irrelevant because the problem is in the input. I want that the program doesn't close when the user press enter in the input of info requested.
import sys
COMBUSTIBLE=chr(raw_input("Introduce unidad de combustible: "))
DURACION=chr(raw_input("Introduce unidad de duracion: "))
if COMBUSTIBLE != "litros" and COMBUSTIBLE != "kilos" and DURACION != "vueltas" and DURACION != "tiempo" and DURACION != "km":
print "Error: Ambos argumentos son invalidos"
print "Primer argumento debe ser 'litros' o 'kilos'"
print "Segundo argumento debe ser 'tiempo' o 'vueltas' o 'km'"
sys.exit(1)
elif COMBUSTIBLE != "litros" and COMBUSTIBLE != "kilos":
print "Error: Primer argumento invalido"
print "Primer argumento debe ser 'litros' o 'kilos'"
sys.exit(2)
elif DURACION != "tiempo" and DURACION != "vueltas" and DURACION != "km":
print "Error: Segundo argumento invalido"
print "Segundo argumento debe ser 'tiempo' o 'vueltas' o 'km'"
sys.exit(3)
else:
pass
# TIPO 1 - LITROS - VUELTAS
if COMBUSTIBLE == "l" and DURACION == "v":
# DATA REQUEST
RACE_DURATION=int(raw_input("Introduce el total de vueltas de la carrera: "))
CAR_FUEL=float(raw_input("Introduce los litros totales del coche: "))
FUEL_PER_LAP=float(raw_input("Introduce el consumo medio en litros por vuelta: "))
The window will be closed right after your proggram finished executing. So if you want the window stays open you should remove sys.exit() statements and add something at the end of your script like:
input("Press any key to exit: ")
in Python 3 or
raw_input("Press any key to exit: ")
in Python 2

NameError: global name 'Circulo_Mohr_v1_2' is not defined

I'm trying make a simple menu (options: 1,2,3) and the second option (input 2) should run a graphical menu.
When I try run python reports a NameError ("global name 'Circulo_Mohr_v1_2' is not defined").
I don't know the correct syntax
print "inicio"
import sys
from librerias import Circ_Mohr_motor_v2
import librerias.Circulo_Mohr_v1_2
from librerias import prueba_importacion
'''
def definicion_ventana():
Circulo_Mohr_v3_0.Ui_CalculodecirculosMohr()
#Ui_CalculodecirculosMohr.setupUi()
'''
def seleccion_de_libreria():
print '''Escoger opcion:
1) motor
2) Ventana
3) test
'''
opcion = raw_input ("Opcion seleccionada: ")
opcion = int (opcion)
if opcion == 1:
print "se ejecuta el motor de calculo"
punto_Ax = raw_input ("Insertar coordenada X de primer punto: ")
punto_Ay = raw_input ("Insertar coordenada Y de primer punto: ")
punto_Bx = raw_input ("Insertar coordenada X de segundo punto: ")
punto_By = raw_input ("Insertar coordenada Y de segundo punto: ")
Circ_Mohr_motor_v2.circulo_mohr(punto_Ax,punto_Ay,punto_Bx,punto_By)
elif opcion == 2:
print "se ejecuta la funcion ventana"
Circulo_Mohr_v1_2.Ui_CalculodecirculosMohr()
print "fin la funcion ventana"
else:
print "se ejecuta el test"
prueba_importacion.prueba_01()
seleccion_de_libreria()
print "fin"
How can I fix that?
try replace
import librerias.Circulo_Mohr_v1_2
with
from librerias.Circulo_Mohr_v1_2 import Ui_CalculodecirculosMohwith
and call directly Ui_CalculodecirculosMohr()
Ui_CalculodecirculosMohr()

Categories