My variable that I created, is not working inside another function - python

I am dealing with a NameError at the moment. I have created multiple functions (for a project that I am working on). A variable that I've created, has to be used in multiple functions. I gave this variable as a parameter in all of the other functions and I had no problem at all. A friend of mine has written the menu function, which I have to connect with the functions I have created. I try to give "antwoorden_list" (which is created inside the function 'vragenLijst') as a parameter, because i need to use this variable inside the "menu" function.. Unfortunately I get this error message;
File "/Users/buni/Desktop/Leiden/IPOHBO/sorteerhoed/sorteerhoed menu.py", line 276, in <module>
main()
File "/Users/buni/Desktop/Leiden/IPOHBO/sorteerhoed/sorteerhoed menu.py", line 271, in main
menu(antwoorden_list)
NameError: name 'antwoorden_list' is not defined
I have no idea why this message is popping, because I have defined antwoorden_list as a parameter.
This is the part of my code which is not working;
##MAIN MENU
def menu(antwoorden_list):
color.write("\n" + "Welkom bij het ICT Sorteerhoed menu " ,"DEFINITION")
color.write(naam + "\n","KEYWORD")
infoApplicatie()
sleep(0.5)
print("_____________________________________\n")
print("1. Quiz beginnen")
print("2. Specialisaties bekijken")
print("3. Resultaten bekijken")
print("4. Programma sluiten")
print("_____________________________________\n")
sleep(0.9)
menuchoice = input("selecteer optie: ")
##SELECTION
if menuchoice == "1":
quiz(antwoorden_list)
elif menuchoice == "2":
specialisatiemenu()
elif menuchoice == "3":
resultatenmenu(antwoorden_list)
elif menuchoice == "4":
exit()
def vragenLijst(antwoorden_list):
print("De vragen worden geladen... ")
sleep(2.0)
print()
print("Goed om te weten: de vragen kunnen alleen beantwoord worden met 'ja' en 'nee', zolang je dit niet invoert, zullen de vragen verder gesteld worden.")
sleep(3.0)
print("---------------------------------------------------------------------------------------------------------------------------------------------------------")
vragen_list = open("vragenspecialisaties.txt").readlines()
vragen_list_index = list(enumerate(vragen_list, 1))
vragen_list_dict = dict(vragen_list_index)
antwoorden_list = []
while vragen_list_dict:
key = choice(list(vragen_list_dict))
antwoord = input(vragen_list_dict[key] + "(ja/nee): ")
if antwoord == "ja" or antwoord == "nee":
antwoorden_list.append((key, antwoord))
antwoorden_list.sort()
del vragen_list_dict[key]
return antwoorden_list
antwoorden_user = open("antwoorden_user.txt", "a")
antwoorden_user.write(naam + ": " + str(antwoorden_list) + "\n")
antwoorden_user.close()
def main():
menu(antwoorden_list)
infoApplicatie()
variabelen(antwoorden_list)
if __name__ == "__main__":
main()
I will appreciate all the help!

When you run your script, the main() function runs at first. So do the variable declarations inside main() before calling the functions.

Related

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.

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: Getting an undefine variable error when trying to call a function?

I'm still pretty new to Python, but it seems I've run into a problem. I get an undefined error when trying to call another function that defines that variable.
def unpackCon():
unpackConfirm = input("Unpack contents?[Y/N] ")
def unpackConScript():
if unpackConfirm == "y":
print ("Unpack confirmed.")
elif unpackConfirm == "n":
print ("Unpack unconfirmed.")
else:
print ("Value %s is not valid.") % (unpackConfirm)
unpackCon()
unpackCon()
unpackConScript()
Knowing Python, it's probably got something to do with indentation and the sorts. At first I believed it was because I called the function without defining it first, but I switched around the orders a bunch of times with no result.
Appreciate an answer!
unpackConfirm is defined inside of unpackCon(), and is out of scope in the other function. You need to return the variable in order to access it.
try:
def unpackCon():
unpackConfirm = input("Unpack contents?[Y/N] ").lower()
return unpackConfirm
def unpackConScript():
unpackConfirm = unpackCon()
if unpackConfirm == "y":
print ("Unpack confirmed.")
elif unpackConfirm == "n":
print ("Unpack unconfirmed.")
else:
print ("Value %s is not valid.") % (unpackConfirm)
unpackCon()
unpackConScript()

Splitting Array into Strings and Displaying Python

So, I'm trying to take information from bookfile.txt and display information from it. So far, I've opened the file. I'm having trouble getting each line as one object of arrayBooks.
I'd like to have arrayBooks[0]="Animal Farm,1945,152,George Orwell"
Then, I'm going to use book1 = arrayBooks[0].split(',') to split it to other information, such as:
book1[0]="Animal Farm"
book1[1]=1945
book1[2]=152
book1[3]="George Orwell"
So, when I want to find the shortest book, I can compare book1[2] to book2[2] and book3[2] to do so.
My main problem is getting the information in the array and usable. Anything I've tried doesn't seem to work and gives an error in the displayAll() function.
I'm using the displayAll() as a control because I feel if I can get the information to display, I will have it to use.
bookfile.txt:
Animal Farm,1945,152,George Orwell
To Kill A Mockingbird,1960,324,Harper Lee
Pride and Prejudice,1813,279,Jane Austen and Anna Quindlen
def main():
print("Welcome!")
displayBookMenu()
populateBooks()
displayAll(populateBooks())
def displayBookMenu:
print("\n1: Display All Books")
print("2: Display Shortest Book")
print("3: Display Longest Book")
print("3: Display Oldest Book")
print("4: Display Newest Book")
print("0: End")
choice = int(input("Choice: "))
if choice == 1:
displayAll()
elif choice == 2:
displayShortest()
elif choice == 3:
displayLongest()
elif choice == 4:
displayOldest()
elif choice == 5:
displayNewest()
elif choice == 0:
exit()
else:
print("Invalid Input")
def populateBooks():
fp = open("bookfile.txt", "r")
return fp.readlines()
def displayAll(arrayBooks):
print ("\nAll Books: \n")
#THIS IS WHERE I GET ERROR vvv
print arrayBooks[0]
def displayShortest():
def displayLongest():
def displayOldest():
def displayNewest():
main()
try this:
lines = [line.strip().split(',') for line in open("books.txt")]
Using list comprehesions you can read your file into a list named lines and convert each line from your files into a list of lists.
These are the results i got when i ran it:
`lines = [line.strip().split(',') for line in open("books.txt")]
print lines
print lines[2]
print lines [2][1]`
enter code here
[['Animal Farm', '1945', '152', 'George Orwell'], ['To Kill A Mockingbird', '1960', '324', 'Harper Lee'], ['Pride and Prejudice', '1813', '279', 'Jane Austen and Anna Quindlen']]
['Pride and Prejudice', '1813', '279', 'Jane Austen and Anna Quindlen']
1813
Now there are a number of edits. Here. Make sure you looks at them carefully:
`def displayBookMenu():
print("\n1: Display All Books")
print("2: Display Shortest Book")
print("3: Display Longest Book")
print("3: Display Oldest Book")
print("4: Display Newest Book")
print("0: End")
choice = int(input("Choice: "))
if choice == 1:
displayAll(populateBooks())
elif choice == 2:
displayShortest()
elif choice == 3:
displayLongest()
elif choice == 4:
displayOldest()
elif choice == 5:
displayNewest()
elif choice == 0:
exit()
else:
print("Invalid Input")
def populateBooks():
lines = [line.strip().split(',') for line in open("books.txt")]
return lines
def displayAll(arrayBooks):
print ("\nAll Books: \n")
#THIS IS WHERE I GET ERROR vvv
for books in arrayBooks:
for each_entry in books:
print each_entry,
print
def displayShortest():
pass
def displayLongest():
pass
def displayOldest():
pass
def displayNewest():
pass
def main():
print("Welcome!")
displayBookMenu()
populateBooks()
main()
Remove displayBooks(populateBooks()) and instead have it in you if choice ==1 statement.
First, you have an error in
def displayBookMenu: #needs ()
And you can't read ArrayBooks because it'a not a global (or nonlocal) variable. I think you have problems with variable scope. Check this: Python variable scope error

How to return value only if a if statement is true?

So I got a piece of code that is providing me with some headache.
def Handy():
print "\nMöchten Sie ein neues Handy?"
print "\n1 - Ja\n2 - Nein"
handy = raw_input(">>> ")
if handy == "2":
print "\nSie möchten kein neues Handy"
elif handy == "1":
wunschhandy = raw_input("\nBitte geben Sie den Namen des Handys ein: ")
else:
Handy()
return handy, wunschhandy
If I choose option "1" everything is ok. But if I go for "2" it gives me this error: "UnboundLocalError: local variable 'wunschhandy' referenced before assignment"
I know why it is happening, or at least I think I know why. It is because the var wunschhandy has not been decleared, because I used option "2".
So how do I solve this problem? Is there a way to only return a value, if it has been assigned by the right if choice?
In your case I would set wunschhandy = None before the if statement.
In this case you have a defined value, and the caller can test for it.
Another option would be
if handy == "2":
print "\nSie möchten kein neues Handy"
return handy,
elif handy == "1":
wunschhandy = raw_input("\nBitte geben Sie den Namen des Handys ein: ")
return handy, wunschhandy
else:
Handy()
which returns a tuple of length 2 for option 1 and a tuple of length 1 for option 2. The caller can easily test that.
Besides, instead of calling Handy() recursively, I would put a loop inside it. Otherwise you might end in a stack overflow error...
If you want to return wunschhandy only if the user chooses "1", then place the return statements within the if blocks
def Handy():
print "\nMöchten Sie ein neues Handy?"
print "\n1 - Ja\n2 - Nein"
handy = raw_input(">>> ")
if handy == "2":
print "\nSie möchten kein neues Handy"
return handy
elif handy == "1":
wunschhandy = raw_input("\nBitte geben Sie den Namen des Handys ein: ")
return handy, wunschhandy
else:
Handy()
//do you want to return Handy()?
Just based on the small snippet of code you provided, it seems the 'wunschhandy' variable is only being defined if 'handy == "1"', but this variable is being returned at the end. I would set wunschhandy equal to null above the if statement so the variable is defined before trying to return it at the end.
It is because the variable wunschhandy is returned before it is declare. Only if you enter 1 it is declared. You may declare the wunschhandy before the if statements and assign it a defualt value.
Just initialise wunschhandy, so it's in the scope:
def Handy():
handy = raw_input("Moechten Sie ein neues Handy?\n1 - Ja\n2 - Nein\n>>> ")
wunschhandy = None
if handy is "2" :
print "\nSie moechten kein neues Handy"
elif handy is "1" :
wunschhandy = raw_input("\nBitte geben sie den Namen des Handys ein: ")
else :
Handy()
return handy, wunschhandy

Categories