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()
Related
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)
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 not sure why it keeps asking to enter a menu choice after I enter one!
When I run it consistently asks me to enter a number, but it doesn't run the functions associated with the numbers
not sure if you needed the class butI included it anyway
import pickle
class Contact:
def __init__(self, name, phone, email):
self.__name = name
self.__phone = phone
self.__email = email
def set_name(self, name):
self.__name = name
def set_phone(self, phone):
self.__phone = phone
def set_email(self, email):
self.__email = email
def get_name(self):
return self.__name
def get_phone(self):
return self.__phone
def get_email(self):
return self.__email
these are the menu options that I have, no matter what number i enter it asks me to enter another number
LOOK_UP = 1
ADD = 2
CHANGE = 3
DELETE = 4
QUIT = 5
FILENAME = 'contacts.txt'
def main():
mycontacts = load_contacts()
choice = 0
while choice != QUIT:
choice = get_menu_choice()
if choice == LOOK_UP:
look_up(mycontacts)
elif choice == ADD:
add(mycontacts)
elif choice == CHANGE:
change(mycontacts)
elif choice == DELETE:
delete(mycontacts)
save_contacts(mycontacts)
def load_contacts():
try:
input_file = open(FILENAME, 'rb')
contact_dct = pickle.load(input_file)
input_file.close()
except:
contact_dct = {}
return contact_dct
def get_menu_choice():
print()
print('Menu')
print('-------------------')
print('1. Look up an contact')
print('2. Add a new contact')
print('3. Change an existing contact')
print('4. Delet a contsct')
print('5. Quit the program')
print()
choice = int(input('Enter your choice: '))
while choice < LOOK_UP or choice > QUIT:
choice = int(input('Enter a vaild choice: '))
return choice
def look_up(mycontacts):
name = input('Enter a name: ')
print(mycontacts.get(name, 'That name is not found'))
def add(mycontacts):
name = input('Name: ')
phone = input('Phone: ')
email = input('Email: ')
entry = contact.Contact(name, phone, email)
if name not in mycontacts:
mycontacts[name] = entry
print('The entry has been added.')
else:
print('That name already exists.')
def change(mycontacts):
name = input('Enter a name: ')
if name in mycontacts:
phone = input('Enter the new phone number: ')
email = input('New Email: ')
entry = contact.Contact(name, phone, email)
mycontacts[name] = entry
print('information updated')
else:
print('not found')
def delete(mycontacts):
name = input('Enter a name: ')
if name in mycontacts:
del mycontacts[name]
print('Entry deleted')
else:
print('That name not found')
def save_contacts(mycontacts):
output_file = open(FILENAME, 'wb')
pickle.dump(mycontacts, output_file)
output_file.close()
main()
I believe the problem is in the following function:
def get_menu_choice():
print()
print('Menu')
print('-------------------')
print('1. Look up an contact')
print('2. Add a new contact')
print('3. Change an existing contact')
print('4. Delet a contsct')
print('5. Quit the program')
print()
choice = int(input('Enter your choice: '))
while choice < LOOK_UP or choice > QUIT:
choice = int(input('Enter a vaild choice: '))
return choice
First issue: If the first choice entered is within bounds, it is never returned from get_menu_choice().
Second issue: If the first choice entered is not within bounds, your while loop just returns the immediate next choice.
How to fix it: Move the return statement outside the while loop in get_menu_choice(). Also, move choice = get_menu_choice() to the bottom of the while loop in main(), and set choice's initial value to get_menu_choice().
Hope this helps.
P.S. What happens if the choice entered by the user is not an integer? What happens if the user enters a character, string, or control character? I would consider additional error-handling for erroneous input.
I need help with a one or two things on my coursework. firstly when I input an incorrect username/password it will output more than one error message at a time. Secondly, when the men function ends the program will go back to the login loop( that allows the user to re-enter their username/password), I have fixed this by using the B variable but this feels extremely janky and I know there is a better way of doing it. Any Modifications or Tips are greatly appreciated (even if they're not related to my above problems). also the way i code is a bit weird so it's probs best you read from bottom to top :)
def quiz():
print ("quiz")# place holder for real code (let's me know the function has been run)
def report():
print ("report") # place holder for real code (let's me know the function has been run)
def a_menu():# Admin menu
print ("Welcome to the student quiz!")
print ("Please choose a option")
while True:
print ("1: Computer science")
print ("2: Histroy")
print ("3: Reports")
menu_in = int(input())
if menu_in == 1:
Comp_sci = True
quiz()
break
elif menu_in == 2:
Hist = True
quiz()
break
elif menu_in == 3:
report()
break
else:
print ("Invalid input! Please try again..")
def menu():
print ("Welcome to the student quiz!")
print ("Please choose a quiz")
while True:
print ("1: Computer science")
print ("2: Histroy")
menu_in = int(input())
if menu_in == 1:
Comp_sci = True
quiz()
break
elif menu_in == 2:
Hist = True
quiz()
break
def login():
b = False
print ("Please enter your username and password")
while True:
if b == True:
break
log_user = input("Username:")
log_pass = input ("Password:")
with open("D:\\Computer science\\Computing test\\logindata.txt","r") as log_read:
num_lines = sum(1 for line in open('D:\\Computer science\\Computing test\\logindata.txt'))
num_lines = num_lines-1
for line in log_read:
log_line = log_read.readline()
log_splt = log_line.split(",")
if log_user == log_splt[0] and log_pass == log_splt[2]:
if log_splt[5] == "a": # Admin will have to mannually change the admin status of other user's through .txt file.
b = True
a_menu()
else:
b = True
log_read.close()
menu()
break
else:
print ("Incorrect username or password, please try again!")
def register():
print ("enter your name, age, and year group and password")
while True:
reg_name = input("Name:")
reg_pass = input ("Password:")
reg_age = input ("age:")
reg_group = input ("Year Group:")
print ("Is this infomation correct?")
print ("Name:",reg_name)
print ("password:",reg_pass)
print ("Age:",reg_age)
print ("Year Group:", reg_group)
reg_correct = input ("[Y/N]").lower()
if reg_correct == "y":
reg_user = reg_name[0:3]+reg_age
reg_write = open("D:\\Computer science\\Computing test\\logindata.txt","a")
reg_write.write (reg_user+","+reg_name+","+reg_pass+","+reg_age+","+reg_group+","+"u"+"\n")
print ("Your username is:",reg_user)
reg_write.close()
login()
break
elif reg_correct == "n":
print ("Please Re-enter your infomation")
else:
Print ("Invalid input! Please try again...!")
def login_ask():
print ("Do you already have an account?")
while True:
ask_in = input("[Y/N]").lower()
if ask_in == "y":
login()
break
elif ask_in == "n":
register()
break
login_ask()