Trying to run a basic search program with Python (beginner level). All other options work (N, Q) but when trying to select S, I receive a nameerror for "plateNum" as not being defined. Even when entering new information, then trying to recall it, it won't allow me to search for the already inputted information.
#mainMenu Function
def displayMainMenu():
print("\nMAIN MENU")
print("(S) Search vehicle by license plate")
print("(N) Add new vehicle")
print("(Q) Quit")
def searchPlate(plateNum, choice):
plateNum = input("Enter 7-DIGIT license plate number: ")
try:
file = open(plateNum + " data.txt", "r")
DataList = file.readlines()
file.close()
except FileNotFoundError:
print("\nContact not found!\n")
else:
print("(P)late Number")
print("(Ma)ke")
print("(Mo)del")
print("(Y)ear")
print("(C)olor")
print("(I)All information")
choice = input(">> ").upper()
print("\n" + plateNum)
if choice == "Ma":
print(DataList[0])
if choice == "Mo":
print(DataList[1])
if choice == "Y":
print(DataList[2])
if choice == "C":
print(DataList[3])
if choice == "I":
print(DataList[0])
print(DataList[1])
print(DataList[2])
print(DataList[3])
#AddVehicle function
def newVehicle():
newPlate = input("Enter license plate of vehicle: ")
newMake = input("Enter Make of vehicle: ")
newModel = input("Enter model of vehicle: ")
newYear = input("Enter year of vehicle: ")
newColor = input("Enter color(s) of vehicle: ")
newList = [newPlate + "\n", newMake + "\n", newModel + "\n", newYear + "\n", newColor + "\n"]
file = open(newPlate + " data.txt", "w")
file.writelines(newList)
file.close()
print("Vehicle Successfully Saved")
#choice
choice = ""
while choice != "Q":
displayMainMenu()
choice = input(">> ").upper()
if choice == "S":
searchPlate(plateNum,choice)
if choice == "N":
newVehicle()
else:
print("Have a nice day!")
while choice != "Q":
displayMainMenu()
choice = input(">> ").upper()
if choice == "S":
searchPlate(plateNum,choice)
platenum isn't defined there in the global scope, that's why you're getting the error. Just change it to
plateNum = ""
while choice != "Q":
displayMainMenu()
choice = input(">> ").upper()
if choice == "S":
searchPlate(plateNum,choice)
or, remove plateNum from the arguments.
You defined searchPlate to take a plate number as an argument, but then you
try to use an undefined variable of the same name to provide that argument, and
you immediately replace whatever value might be passed with a new input.
You do the same thing with choice; that name is at least defined when you call searchPlate, but you don't need to pass its value to the function.
Replace the definition of searchPlate with
def searchPlate(plateNum):
try:
file = open(plateNum + " data.txt", "r")
DataList = file.readlines()
file.close()
except FileNotFoundError:
print("\nContact not found!\n")
else:
...
then replace its use with something like
if choice == "S":
x = input("Enter 7-DIGIT license plate number: ")
searchPlate(x)
Related
New to programming and trying to learn how to store data using pickle. Essentially, what I'm trying to do is create an address book using classes stored in a dictionary. I define the class (Contact). It all worked, but when I tried to introduce pickling to store data from a previous session, I've created 2 errors that I've found so far.
1: If I select to load a previous address book, I cant update or view the class variables. It's almost like there are two different dictionaries.
2: I select not to load a previous address book and add a contact. When I add the contact and try to view the contacts, I'll get an "Unbound Error: local variable 'address book' referenced before assignment"
What am I doing wrong with pickling?
address_book= {}
class Contact:
def __init__(self,first_name,last_name, phone,company):
self.first_name = first_name
self.last_name = last_name
self.phone = phone
self.company = company
def __call__(self):
print("Contact: %s \nPhone #: %s \nCompany: %s" %(self.name,self.phone,self.company))
def erase(entry):
del address_book[entry] # delete address book entry
del entry #delete class instance
def save():
new_file = open("addressBook.pkl", "wb")
saved_address = pickle.dump(address_book, new_file)
new_file.close()
def load():
open_file = open("addressBook.pkl", "rb")
address_book = pickle.load(open_file)
open_file.close()
print(address_book)
return address_book
def add_contact():
first_name = input("Please type the first name of the contact. ")
last_name = input("Please type in the last name of the contact. ")
if " " in first_name or " " in last_name:
print("Please do not add spaces to your first or last name.")
else:
phone = input("Please type the user phone number without hyphens. ")
if not phone.isnumeric():
print("That isn't a valid phone number.")
else:
company = input("Please type the company they work for. ")
contact = Contact(first_name,last_name,phone,company)
address_book[first_name + " " +last_name] = contact #assign key[first and last name] to value[the class instance] in dictionary
def view_contact(entry):
if entry in address_book:
print("First Name: %s" %(address_book[entry].first_name)) #get class variables
print("Last Name: %s" %(address_book[entry].last_name))
print("Phone Number: %s" %(address_book[entry].phone))
print("Company: %s" %(address_book[entry].company))
else:
print("That person isn't in your address book")
def update(entry):
if entry in address_book:
update_choice = input("Would you like to update the first name (f), last name (l), phone (p), or company (c)? ").lower()
if update_choice == "f":
address_book[entry].first_name = input("Please type the updated first name of this contact. ")
updated_key = address_book[entry].first_name + " " + address_book[entry].last_name
address_book[updated_key] = address_book[entry]
del address_book[entry] #delete old key
elif update_choice == "l": #update last name
address_book[entry].last_name = input("Please type the updated last name of this contact. ")
updated_key = address_book[entry].first_name + " " + address_book[entry].last_name
address_book[updated_key] = address_book[entry]
del address_book[entry]
elif update_choice == "p":
address_book[entry].phone = input("Please type the updated phone number of this contact. ")
elif update_choice == "c":
address_book[entry].company = input("Please type the updated company of this contact. ")
else:
print("That was not valid. Please try again.")
def main():
print("Welcome to your address book!!")
returning_user = input("Would you like to load a previous address book? Y or N ").lower()
if returning_user == "y":
address_book = load()
while True:
choice = input("Please type A:Add, B:View All Contacts, V:View a Contact, D:Delete, U:Update, or X:Exit ").lower()
if choice == "x":
break
elif choice == "a":
add_contact()
elif choice == "b":
if len(address_book) == 0: #error check if no contacts
print("You don't have any friends. PLease go make some and try again later. :(")
else:
for i in address_book:
print(i)
elif choice == "v":
if len(address_book) == 0:
print("You don't have any friends. PLease go make some and try again later. :(")
else:
view = input("Who do you want to view? Please type in their first and last name. ")
view_contact(view)
elif choice == "d":
if len(address_book) == 0:
print("You don't have any friends. PLease go make some and try again later. :(")
else:
contact = input("Please type the first and last name of the person you want to delete ")
if contact in address_book:
erase(contact)
elif choice == "u":
if len(address_book) == 0:
print ("C'mon, you don't know anyone yet. How about you make some friends first?")
else:
choice = input("What is the first and last name of the person you'd like to update? ")
update(choice)
else:
print("That was not valid. Please try again.")
print()
save_book = input("Would you like to save your book? Y or N ").lower()
if save_book == "y":
save()
print("Thanks for using the address book!")
main()
I declared the view_songs() function which I want to use separately and I also want to use it inside another function add_songs() with a conditional, after the code which does the part of adding songs to the collection.
user_input = input('Enter "a" to add songs,"f" to find existing songs,"v" to view entire collection and "q" to quit :')
while user_input != "q":
if user_input == "v":
def view_songs():
for song in enumerate(Songs_collection, 1):
print(song)
view_songs()
elif user_input == "a":
def add_songs():
elements_in_list = len(Songs_collection)
song_name = input('Enter the name of the song to be added to the collection: ')
song_artist = input('Enter the name of the artist of the song which was added previously :')
Songs_collection.insert(elements_in_list, ({elements_in_list + 101: f'{song_name}', f'{elements_in_list + 101}_Artist': f'{song_artist}'}))
print('Song added to the collection!')
post_add_input = input('Press "v" to print whole collection or "q" to quit:')
if post_add_input == "v":
view_songs()
elif post_add_input == "q":
print('Quitting loop...')
else:
print('Invalid Input')
add_songs()
It gives me an error which says free variable view_songs referenced before assignment in the enclosing scope. How can I go about to using this function inside add_Songs()?
As per my comment above this should hopefully solve the issues you're having?
def view_songs():
for song in enumerate(Songs_collection, 1):
print(song)
def add_songs():
elements_in_list = len(Songs_collection)
song_name = input('Enter the name of the song to be added to the collection: ')
song_artist = input('Enter the name of the artist of the song which was added previously :')
Songs_collection.insert(elements_in_list, ({elements_in_list + 101: f'{song_name}', f'{elements_in_list + 101}_Artist': f'{song_artist}'}))
print('Song added to the collection!')
post_add_input = input('Press "v" to print whole collection or "q" to quit:')
if post_add_input == "v":
view_songs()
elif post_add_input == "q":
print('Quitting loop...')
else:
print('Invalid Input')
while user_input != "q":
if user_input == "v":
view_songs()
elif user_input == "a":
add_songs()
#Some way to redefine user_input?
#user_input = input()
I'm trying to call the "name" under 'create():' in 'show():', but it says it's not defined. How can I save my input in 'create():', so I can use it in the other subroutines (in 'show():' for this example).
Thank you
I have tried to ask the user input after the choice part, but it doesn't solve it. I keep getting the same error.
import sys
class data:
name = ""
average = ""
def menu():
print("1) Data input")
print("2) Print data")
print("3) Give file name")
print("4) Save")
print("5) Read file")
print("0) Stop")
choice = int(input("Give your choice: "))
print()
return choice
def save(datalist, namea):
f = open(namea, "w")
for data in datalist:
row = str("{};{}").format(data.name, data.average)
f.write(row)
f.write("\n")
f.close()
def read(datalist, namea):
f = open(namea, "r")
for row in f:
row = row.split(";")
dataa = data()
dataa.name = str(row[0])
dataa.average = float(row[1])
datalist.append(dataa)
return datalist
def printt(datalist):
for data in datalist:
print(data.name, data.average)
def name():
namea = str(input("Give a name: "))
return namea
def inputt(datalist):
dataa = data()
dataa.name = str(input("Give a name: "))
dataa.average = float(input("Give the average (float): "))
datalist.append(dataa)
print()
return(datalist)
def main():
try:
datalist = []
while True:
choice = menu()
if (choice == 1):
datalist = inputt(datalist)
elif (choice == 2):
printt(datalist)
elif (choice == 3):
namea = name()
elif (choice == 4):
save(datalist, namea)
elif (choice == 5):
datalist = read(datalist, namea)
elif (choice == 0):
print("The program was closed {} at {}".format(datetime.datetime.now().strftime('%d.%m.%Y'), datetime.datetime.now().strftime('%H:%M:%S')))
return False
except Exception:
sys.exit(0)
main()
I excpect it to print the name I input in 1), when I call 2).
For example:
choice 1)
1) Give name: Daniel
choice 2)
2) Prints: Hello Daniel
you got a problem with your Scope.
The name variable is only local.
See https://www.programiz.com/python-programming/global-local-nonlocal-variables for more Information.
a hotfix would be using global-variables instead, or as Aaron D. Rodriguez suggested passing the name as parameter to the show-function.
def lista():
print("1) Write name.")
print("2) Print written name.")
print("0) Stop.")
choice = int(input("Give your choice: "))
return choice
def create():
global name
name = input("Give name: ")
return(name)
def show():
global name
print(name)
return
def main():
print("Choose from the following list:")
while True:
choice = lista()
if (choice == 0):
print("Thanks for using the program!")
break
elif (choice == 1):
create()
elif (choice == 2):
show()
else:
print("Input not detected.\nStopping.")
break
main()
You would have to have show() include a parameter in it. For example:
def show(n):
print(n)
So that when you call show(n), it prints whatever you include as n.
So if you called show(name). It would print out name.
def show(n):
print(n)
show(name) #This would print out name.
You also don't need return unless you are returning a value. Return doesn't make the code go back, it just makes the function return a value. So you do need return for list() and create(), but not for show(n).
Edit
You also would want to set the user input as a variable when you call create.
def main():
print("Choose from the following list:")
while True:
choice = lista()
if (choice == 0):
print("Thanks for using the program!")
break
elif (choice == 1):
name = create() #Here is where you should change it
elif (choice == 2):
show(name)
else:
print("Input not detected.\nStopping.")
break
I'm trying to create an encryption program that is also capable of using a username and password to be accessed, alongside the password being able to be changed, however, I am getting the following error when trying to read the password from a file.
Traceback (most recent call last):
File "C:/Users/Matthew/AppData/Local/Programs/Python/Python37-32/a.py", line 28, in <module>
password()
File "C:/Users/Matthew/AppData/Local/Programs/Python/Python37-32/a.py", line 9, in password
var2 = open("Users\Matthew\AppData\Local\Programs\Python\Python37-32\password.txt","r")
FileNotFoundError: [Errno 2] No such file or directory: 'Users\\Matthew\\AppData\\Local\\Programs\\Python\\Python37-32\\password.txt'
Password is saved in the Users\Matthew\AppData\Local\Programs\Python\Python37-32\password.txt directory.
Below is the code.
import os
import time
def password():
while True:
username = input ("Enter Username: ")
password = input ("Enter Password: ")
var1 = "admin"
var2 = open("Users\Matthew\AppData\Local\Programs\Python\Python37-32\password.txt","r")
if username == var1 and password == var2:
time.sleep(1)
print ("Login successful!")
answer = input("Do you wish to change your password (Y/N): ")
if input == "Y" or "y":
var2 = input("Enter new password: ")
elif input == "N" or "n":
break
logged()
break
else:
print ("Password did not match!")
def logged():
time.sleep(1)
print ("Welcome to the encryption program.")
password()
def main():
result = 'Your message is: '
message = ''
choice = 'none'
while choice != '-1':
choice = input("\nDo you want to encrypt or decrypt the message?\nEnter 1 to Encrypt, 2 to Decrypt, -1 to Exit Program: ")
if choice == '1':
message = input("\nEnter the message to encrypt: ")
for i in range(0, len(message)):
result = result + chr(ord(message[i]) - 2)
print (result + '\n\n')
result = ''
elif choice == '2':
message = input("\nEnter the message to decrypt: ")
for i in range(0, len(message)):
result = result + chr(ord(message[i]) + 2)
print (result + '\n\n')
result = ''
elif choice != '-1':
print ("You have entered an invalid choice. Please try again.\n\n")
elif choice == '-1':
exit()
main()
Any help is appreciated, thanks!
Provide the complete path:
var2 = open("C:/Users/Matthew/AppData/Local/Programs/Python/Python37-32/password.txt","r")
Edit:
As you said in the comment that it worked but the password was marked as incorrect, so I have fixed issues with your code.
You cannot read data directly by opening a file. You will have to use the command read to get the data:
file = open("C:/Users/Matthew/AppData/Local/Programs/Python/Python36/password.txt","r")
var2 = file.read()
file.close()
Your second code problem is setting new password. The code you made:
answer = input("Do you wish to change your password (Y/N): ")
if input == "Y" or "y":
var2 = input("Enter new password: ")
elif input == "N" or "n":
break
Don't use input to see the value, use the variable in which you stored the input data. Also lower the string to make it easy:
answer = input("Do you wish to change your password (Y/N): ")
if answer.lower() == "y":
var2 = input("Enter new password: ")
elif answer.lower() == "n":
break
The full code can be like:
import os
import time
def password():
while True:
username = input ("Enter Username: ")
password = input ("Enter Password: ")
var1 = "admin"
file = open("C:/Users/Matthew/AppData/Local/Programs/Python/Python36/password.txt","r")
var2 = file.read()
file.close()
if username == var1 and password == var2:
time.sleep(1)
print ("Login successful!")
answer = input("Do you wish to change your password (Y/N): ")
if answer.lower() == "y":
var2 = input("Enter new password: ")
elif answer.lower() == "n":
break
logged()
break
else:
print ("Incorrect Information!")
def logged():
time.sleep(1)
print ("Welcome to the Encryption program.")
password()
def main():
result = 'Your message is: '
message = ''
choice = 'none'
while choice != '-1':
choice = input("\nDo you want to encrypt or decrypt the message?\nEnter 1 to Encrypt, 2 to Decrypt, -1 to Exit Program: ")
if choice == '1':
message = input("\nEnter the message to encrypt: ")
for i in range(0, len(message)):
result = result + chr(ord(message[i]) - 2)
print (result + '\n\n')
result = ''
elif choice == '2':
message = input("\nEnter the message to decrypt: ")
for i in range(0, len(message)):
result = result + chr(ord(message[i]) + 2)
print (result + '\n\n')
result = ''
elif choice != '-1':
print ("You have entered an invalid choice. Please try again.\n\n")
elif choice == '-1':
exit()
main()
I'm writing this program that lets users choose an option to display, change,add, remove, write or quit
I keep getting invalid syntax error on this elif statement in my program and i dont know why?
DISPLAY = 'D'
CHANGE = 'C'
ADD = 'A'
REMOVE = 'R'
WRITE = 'W'
QUIT = 'Q'
#main function
def main ():
print()
print()
print('\t Wombat Valley Tennis Club')
print('\t Member Register')
print('\t =======================')
main_dic = {}
with open ('wvtc_data.txt','r')as x:
for line in x:
line = line.rstrip ('\n')
items = line.split (':')
key,value = items[0], items[1:]
main_dic[key] = values
choice = input('choice: ')
while choice != QUIT:
choice = get_menu_choice()
if choice==DISPLAY:
display(main_dic)
elif choice==CHANGE:
change(main_dic)
elif choice== REMOVE:
remove (main_dic)
elif choice==WRITE:
write(main_dic)
def get_menu_choice():
print()
print("\t\t Main Menu")
print()
print('\t<D>isplay member details')
print('\t<C>hange member details')
print('\t<A>dd a new member')
print('\t<R>emove a member')
print('\t<W>rite updated details to file')
print('\t<Q>uit')
print()
print('Your choice (D, C, A, R, W OR Q)?\t[Note: Only Uppercase]')
print()
choice = input("Enter your choice: ")
while choice < DISPLAY and choice < CHANGE or choice > QUIT:
choice = input ('Enter your choice: ')
return choice
def display(main_dic):
name = input('Type the name of the member:')
print()
print (main_dic.get(name, 'not found!'))
print()
print()
def change(main_dic):
name=input("Enter the member number")
print()
print(main_dic.get(name,'not found!'))
print()
NAME = 1
EMAIL = 2
PHONE = 3
print('Please select')
print('==============')
print('Change Name<1>')
print('Change E-mail<2>')
print('Change Phone Number<3>')
print()
if choose == NAME:
new_name = input('Enter the name: ')
print()
print("Data has been changed")
main_dic[name][0]=new_name
print (mem_info[name])
print()
elif choose == EMAIL:
new_email=input('Enter the new email address:')
print ('Email address has been changed')
#change the data
main_dic[name][1]=new_email
print(mem_info[name])
print()
elif choose == PHONE:
new_phone = int (input('Enter the new phone number'))
print ("phone number has been changed")
main_dic[name][2]=new_phone
print(main_dic[name])
print
def write(main_dic):
print()
name = input ("Enter the name of a member:")
print()
print (mem_info.get(name,'Not found!'))
print()
main()
main()
Also any help or suggestions in making this code work are appreciated.
It's a formatting problem. The elifs have to start in the same column as the if to which they belong.
Example
if something:
do_somtething()
elif something_else:
do_the_other_thing()