Python file executable error - python

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

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

Getting unittest assert.Equal returns failure when it shouldn't

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.

applying a QUIT function to mini game in python

So I just started with python and I received the following task;
I need to create a mini game where the game choses a random number from 0-10.
Now I got most of my code but it seems I keep having issues with implementing a Quit option.
So the point is that the player can at any time give Quit as an answer and then the game quits.
It seems I can not attribute Quit in the right way.
When typing the Quit command (nee) I keep getting the following error message;
**Traceback (most recent call last):
File "C:\Users\aarabsa\PycharmProjects\projecten1\Lotto1.2.py", line 22, in <module>
guess = int(input('Probeer opnieuw of typ nee om het spel te verlaten: '))
ValueError: invalid literal for int() with base 10: 'nee'**
Could any of you guys give some advise ?
import random
import sys
print("Hello, wat is uw naam?")
naam = input()
print("Kan je de juiste cijfer raden tussen 0 en 10?")
answer = random.randint(0, 10)
guess = int(input('geef uw gekozen nummer: '))
TotalGuesses = 0
while guess != answer:
TotalGuesses += 1
if guess < answer:
print('fout antwoord!')
guess = int(input('Probeer opnieuw of typ nee om het spel te verlaten: '))
if guess in ['nee']:
print('Jammer dat je nu al opgeeft ' + naam + ', tot de volgende keer!')
sys.exit()
elif guess > answer:
print('fout antwoord!')
guess = int(input('Probeer opnieuw of typ nee om het spel te verlaten: '))
if guess in ['nee']:
print('Jammer dat je nu al opgeeft ' + naam + ', tot de volgende keer!')
sys.exit()
if guess == answer:
break
if guess == answer:
print('Correct ' + naam + '! Je hebt ' + str(TotalGuesses) + 'foutief geraden voordat je de juiste antwoord kon vinden!')
You should convert to an int only if you've first made sure the user didn't enter that string. For example:
guess = None # So it's defined
guess_string = input('geef uw gekozen nummer: ')
if guess_string.lower() == 'nee':
... # tell the user goodbye, or whatever
sys.exit()
else:
guess = int(guess_string)
Additionally, you could check that their input is a valid number before converting it and assigning it to guess. Here is an explanation of how you can do that.
Since you get user input multiple times in your program, you could wrap all that up in a function and just call that, so you don't have repeats in your code.

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

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