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()
Related
I dont understand why it doesnt print the sentence. I have tried everything i can think off but im new to python is there something im missing?
def main():
print("1 = USD 2= GB pounds 3 = Japanse Yen")
valuta = input(" Welke valuta wilt u in wisselen voor de euro (graag het getal geven) ")
if __name__ == "__main__":
main()
Try changing your code to:
def main():
print("1 = USD 2= GB pounds 3 = Japanse Yen")
valuta = input(" Welke valuta wilt u in wisselen voor de euro (graag het getal geven) ")
print(valuta)
if __name__ == "__main__":
main()
I am very new to python and have been tasked with using unittest for my code,
my code is as follows:
import platform
import os
OpSys=platform.system()
def clear ():
if (OpSys=="Windows"):
os.system("cls")
else:
os.system("clear")
def ShowPlaca(type):
if (type!=""):
print("\nLa placa pertenece a", type)
else:
print("\nPlaca no reconocida")
class Placa:
def TypePlaca(self):
placa=input("\nIngrese una placa: ")
if re.match("^([A-Z]|[0-9]){6}$", placa):
print("\nIngresaste una placa")
if re.match("^MA([A-Z]|[0-9]){4}$", placa):
type=("una motocicleta")
elif re.match("^MB([A-Z]|[0-9]){4}$", placa):
type=("un MetroBus")
elif re.match("^TA([A-Z]|[0-9]){4}$", placa):
type=("un taxi")
elif re.match("^E([A-Z]{1}|[0-9])+", placa):
type=("un vehiculo fiscal o judicial")
elif re.match("^CP([A-Z]|[0-9])+", placa):
type=("un vehiculo del canal")
elif re.match("^BU( |[0-9]{4})+$", placa):
type=("un Bus")
elif re.match("^HP( |[0-9]{4})+$", placa):
type=("un radioaficionado")
elif re.match("^A([A-Z]{1}|[0-9]{4})+$", placa):
type=("un auto regular")
elif re.match("^CC([A-Z]|[0-9])+$", placa):
type=("un cuerpo consular")
elif re.match("[0-9]+$", placa):
type=("una serie antigua")
elif re.match("^PR([A-Z]|[0-9])+", placa):
type=("un auto de prensa")
else:
type=("")
ShowPlaca(type)
else:
print ("Placa no valida")
placa=Placa()
if __name__=="__main__":
n=0
while n==0:
print(" \n Las placas siguen este formato:")
print("\n\nMoto: MA####\nAuto Regular: A(A-G)###")
print("Autos de prensa: PR####\nCuerpo Consular: CC####")
print("Radioaficionado: HP####\nBus: BU####")
print("Fiscal : E(A-Z)####\nTaxi: TA####\nMetroBus: MB####")
print("Las placas antiguas se conforman de 6 numeros.")
print("\n")
placa.TypePlaca()
print ("\nPresione 1 para hacer otra consulta o 2 para salir")
x = input ()
if x == '2':
n += 1
elif x == '1':
clear ()
exit ()
Please excuse the Spanish, this is how I have been trying to test it:
UPDATED
import unittest
from placas2 import TypePlaca
class Testplacas2(unittest.TestCase):
def test_TypePlaca(self):
placa = "123456"
self.assertEqual(placa.TypePlaca ,"una serie antigua...")
if __name__ == '__main__':
unittest.main()
When I try to run it gives me the following error:
Traceback (most recent call last):
File "C:\Users\movid\Documents\Programacion 3\Final\source\test_placas2.py", line 2, in <module>
from placas2 import TypePlaca
ImportError: cannot import name 'TypePlaca' from 'placas2' (C:\Users\movid\Documents\Programacion 3\Final\source\placas2.py)
To make things clear I have to test the 10 different types of car plates and see if that would give me the given result, while operating the program if my input is 123456, it does return "una serie antigua..." but most likely I need help structuring my test differently to get the result Im looking for.
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()
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
I have this code wrote in Python:
liste_usager = input("Veuillez entrer la liste d'entiers:")
liste = []
for n in liste_usager.split(' '):
liste.append(int(n))
print(liste)
return liste
print('liste enregistrée')
print('que voulez-vous faire?')
boucle = True
while boucle:
print('''
1-afficher la liste
2-trier la liste
3-afficher la valeur maximale
4-afficher la valeur minimale
5-afficher la somme des valeurs
6-inverser la liste
7-modifier la liste
0-retour
''')
choix= input('choissisez une commande:')
if choix =='1':
print(liste_usager)
if choix =='2':
menu_tri()
else:
boucle= False
this just return a list of integer such as [1,2,3]. My problem is that I have other def function/module in this same .py file,and those module needs to use the resulting list of this gestionliste() module.For example a module sort the list,but how to keep the list or transfer it to other modules/functions without asking it again to the user? Thanks!
Return the list from the function, and pass it to other functions.
At the bottom of your function, add
return liste
When you call the function, use:
liste = gestionliste();
When you call a new function, pass it in like this:
otherFunction(liste)
Of course your other function must take it as a parameter.
def otherFunction(liste):
# You can now use liste inside this function.
You have the return the result list.
def gestionliste():
liste_usager = input("Veuillez entrer la liste d'entiers:") #user enter number(s) of his choices
liste = []
for n in liste_usager.split(' '):
liste.append(int(n))
return liste
In your original copy of code, you did not return anything explicitly. So by default, it return None.
And to use the result in another function, to say func2, you could do like:
temp = gestionliste()
func2(temp)
Just change your print to return
def gestionliste():
liste_usager = input("Veuillez entrer la liste d'entiers:") #user enter number(s) of his choices
# I used list comprehension instead of your for loop
liste = [int(n) for n in liste_usager.split(' ')]
return liste
Return liste from the function.
Example:
# In function definiton file
def gestionliste():
liste_usager = input("Veuillez entrer la liste d'entiers:") #user enter number(s) of his choices
liste = []
for n in liste_usager.split(' '):
liste.append(int(n))
return liste
# In your main script
liste = gestionliste()