How can I repeat a function in python 3? - python

So here is my code:
membership_data = open("C:\\Users\\user\Desktop\Pre-release\membership_data.txt", "w")
def ValidateMemberID(MemberID):
if len(MemberID) !=6:
return("Wrong Format")
elif MemberID[:1] == (MemberID[:1]).lower():
return("Wrong Format")
elif MemberID[1:3] == (MemberID[1:3]).upper():
return("Wrong Format")
elif (MemberID[3:]).isdigit() == False:
return("Wrong Format")
else:
return("Correct Format")
def inputdata():
Name = input("Please input member name")
MemberID = input("Please input member ID")
ValidateMemberID(MemberID)
if ValidateMemberID(MemberID) == "Correct Format":
NameID = [Name, MemberID, "\n"]
else:
print ("Invalid MemberID")
membership_data.writelines(NameID)
for _ in range(5):
do()
inputdata(_)
membership_data.close
The issue I get is:
Traceback (most recent call last):
File "C:\Users\user\Desktop\Pre-release\task_3.1.py", line 31, in <module>
do()
NameError: name 'do' is not defined
What I want to do is to input 5 different records upon the first instance of my program. Essentially I need to run inputdata() for 5 times. However, my for in range do function keeps giving back this error. I tried different ways of writing it but to no avail.

I think you must delete 'do()' from your code
for x in range(5):
inputdata()
membership_data.close()

Related

Adding and saving to list in external json file

I'm very new to Python and I'm struggling when it comes to saving the data that the user has entered to a json file when quitting the application. Also every time I run my code all the data inside the json file is wiped. When I enter the input to save and exit I get this error code:
Traceback (most recent call last):
File "C:\Users\User\Downloads\sit_resources\sit_resources\sit_admin_application.py", line 86, in <module>
main_menu()
File "C:\Users\User\Downloads\sit_resources\sit_resources\sit_admin_application.py", line 23, in main_menu
save()
File "C:\Users\User\Downloads\sit_resources\sit_resources\sit_admin_application.py", line 82, in save
patients_file.write(finallist)
io.UnsupportedOperation: not writable
Here is my code below:
import json
patients_file = open("patients.json", "r")
loaded_patients = json.load(patients_file)
def main_menu():
'''Function docstring documentation here'''
print("\nSIT Data Entry Menu")
print("==========================")
print("1: Print Patients' List\n2: Add Patient\n3: Delete Patient\n4: Exit")
print("==========================")
input1 = input("Enter your menu selection:")
if input1 == "1":
patients_list()
elif input1 == "2":
add_patient()
elif input1 == "3":
remove_patient()
elif input1 == "4":
save()
else:
print ("Please enter a valid input")
main_menu()
def patients_list():
print("\nSIT current patients:\n")
loaded_patients.sort(key=str.casefold)
for number, item in enumerate(loaded_patients, start=1):
print(number, item)
print("\nTotal number of registered patients is", len(loaded_patients))
main_menu()
def add_patient():
newpatient = input("\nEnter new Patient -> Lastname Firstname:")
print ("Do the details you have entered look correct? y/n")
confirm = input()
if confirm == "y":
loaded_patients.append(newpatient)
print ("Patient successfully added to list")
main_menu()
elif confirm == "n":
print ("Patient import cancelled")
add_patient()
else:
print ("Please enter a valid input")
add_patient()
def remove_patient():
print ("Which of the following patients would you like to remove?")
loaded_patients.sort(key=str.casefold)
for number, item in enumerate(loaded_patients, start=1):
print(number, item)
try:
removepatient = int(input("\nEnter the number of the patient you would like to remove"))
print ("Does the patient number you have entered look correct? y/n")
delconfirm = input()
if delconfirm == "y":
try:
removepatient = (removepatient - 1)
loaded_patients.pop(removepatient)
print ("Patient was successfully removed from the list")
main_menu()
except IndexError:
print("Please enter a valid input")
remove_patient()
elif delconfirm == "n":
print ("Deletion cancelled")
remove_patient()
else:
print ("Please enter a valid input")
remove_patient()
except ValueError:
print ("Please enter a valid input")
remove_patient()
def save():
open("patients.json", "w")
finallist = json.dumps(loaded_patients)
patients_file.write(finallist)
print("Patient List successfully saved")
quit()
main_menu()
I store the json file in the same directory and all it contains is a list:
["Soreback Leigh", "Neckache Annette", "Sorefoot Jo", "Kaputknee Matt", "Brokentoe Susan", "Tornligament Alex"]
If anyone could help me out and let me know what I'm doing wrong or any simpler method I could use, it would be greatly appreciated.
Thanks
Your code has several issues, including the one you're asking about.
The main thing is the overall structure: your code keeps calling functions from functions, never really returning - that can work for a very long time, but in the end it will fail, and it's not the correct way to go about this.
Take for example your main_menu() - once an option is selected, you call the function matching it, and when the work there is done, you call main_menu() again. However, a better way to do the same:
def main_menu():
choice = ''
while choice != '4':
print('some options, 4 being "save and quit"')
if choice == 1:
patients_list()
...
# no if choice == 4: save() here, we'll save at the end
save()
This way, the menu will keep getting printed when you return to it, but every function that is executed, is allowed to return and then the loop restarts, unless option 4 was entered. And since you can allow the functions to return, no need to call main_menu() at the end of them.
Your save() function has some issues: it doesn't need quit() any more, but you also didn't do anything with the file you opened. A nice way to do this in Python is to use a 'context manager', which boils down to using with, like this:
def save():
with open("patients.json", "w") as patients_file:
finallist = json.dumps(loaded_patients)
patients_file.write(finallist)
That's assuming your loaded_patients always contains all the current patients of course. Given that's what it is for, you should consider just calling it patients.
Your file only contains a list, because a list is what you are creating in those functions and a list is a valid content for a json file. If you expected a dictionary, you should construct one in the rest of the code, but from your example it's unclear what exactly you would expect that dictionary to look like.
The conventional way to load and save json:
with open('patients.json', 'r') as f:
loaded_patients = json.load(f)
with open('patients.json', 'w') as f:
json.dump(loaded_patients, f)
You are trying to write to patients_file, which you opened in read-only mode.

How to solve python's NameError: name 'xx' is not defined?

I am learning python, according to the logic written in the code in the book, I want to see the running result, the code is as follows, but the output error NameError: name 'pr' is not defined
code show as below:
stack=[]
def pushit():
stack:append(input(' Enter New String: ').strip())
def popit():
if len(stack)==0:
print('Cannot pop from an empty stack!')
else:
print ('Removes [','stack.pop()',']')
def viewstack():
print(stack)
CMDs={'u':pushit,'o':popit,'v':viewstack}
def showmenu():
pr='''
p(U)sh
p(O)p
(V)iew
(Q)uit
Enter choice:'''
while True:
while True:
try:
choice=input(pr).strip()[0].lower()
except (EOFError,KeyboardInterrupt,IndexError):
choice='q'
print('\nYou picked:[%s]'%choice)
if choice not in 'uovq':
print('Invalid option,try again')
else:
break
if choice=='q':
break
CMDs[choice]()
if _name_=='_main_':
showmenu()
The error message is as follows:
Traceback (most recent call last):
File "/Users/zego/Desktop/test.py", line 22, in <module>
choice=input(pr).strip()[0].lower()
NameError: name 'pr' is not defined
You have not inserted the showmenu function code at right index. The while loop should be started from one tab space ahead.
Look at the below code.
stack=[]
def pushit():
stack:append(input(' Enter New String: ').strip())
def popit():
if len(stack)==0:
print('Cannot pop from an empty stack!')
else:
print ('Removes [','stack.pop()',']')
def viewstack():
print(stack)
CMDs={'u':pushit,'o':popit,'v':viewstack}
def showmenu():
pr='''
p(U)sh
p(O)p
(V)iew
(Q)uit
Enter choice:'''
while True:
while True:
try:
choice=input(pr).strip()[0].lower()
except (EOFError,KeyboardInterrupt,IndexError):
choice='q'
print('\nYou picked:[%s]'%choice)
if choice not in 'uovq':
print('Invalid option,try again')
else:
break
if choice=='q':
break
CMDs[choice]()

Rewriting CSV file in Python messes up index of rows

This is my entire project at the moment. The original CSV file has 4 rows with a contacts name, email, and phone information. The "list" "view" and "add" functions work fine until I use the "delete" function. In order to delete the desired line, I put the file in a list, deleted the row the user inputs, and rewrote the list into the CSV file with what appears to be good format.
import csv
print("Contact List\n")
print(" list - Display all contacts\n","view - View a contact\n","add - Add a contact\n", "del - Delete a contact\n", "exit - Exit program\n")
def main():
userCom = input("\nCommand: ")
if userCom == "list":
lists()
elif userCom == "view":
count()
elif userCom == "add":
add()
elif userCom == "del":
delete()
elif userCom == "exit":
exitt()
else :
print("Invaild input, try again")
main()
def count():
counter = 1
with open("contacts.csv") as file:
number = file.readline()
for line in file:
counter = counter +1
view(counter)
def lists():
with open("contacts.csv", newline="") as file:
reader = csv.reader(file)
counter = 0
for row in reader:
print(int(counter) + 1, ". ",row[0])
counter = counter+1
main()
def view(count):
num = input("Enter a contact's number to view their information: ")
while num.isdigit() == False or int(num) < 1 or int(num) > int(count):
print("Invaild input, try again")
view(count)
reader = csv.reader(open("contacts.csv"))
lines = list(reader)
print("Name: ",lines[int(num)-1][0],"\nEmail: ",lines[int(num)-1][1],"\nPhone Number: ",lines[int(num)-1][2])
main()
def add() :
name = input("Name: ")
email = input("Email: ")
phone = input("Phone: ")
added = [name,",",email,",",phone]
with open("contacts.csv", "a") as file:
for item in added:
file.write(item)
print(name, " was added.")
file.close()
main()
def delete():
deleted = input("Enter number to delete: ")
reader = csv.reader(open("contacts.csv"))
contacts = list(reader)
del contacts[int(deleted)-1]
with open("contacts.csv", "w") as file:
writer = csv.writer(file)
writer.writerows(contacts)
print("Number ",deleted," was deleted.")`enter code here`
file.close()
main()
main()
When I use delete and try the "list" or "view" features, I get this error message:
Traceback (most recent call last):
File "C:\Users\Test\Desktop\contacts_1.py", line 81, in <module>
main()
File "C:\Users\Test\Desktop\contacts_1.py", line 15, in main
delete()
File "C:\Users\Test\Desktop\contacts_1.py", line 72, in delete
main()
File "C:\Users\Test\Desktop\contacts_1.py", line 9, in main
lists()
File "C:\Users\Test\Desktop\contacts_1.py", line 35, in lists
print(int(counter) + 1, ". ",row[0])
IndexError: list index out of range
Any help helps!
This is because your row doesnt contain any line, so it doesn't even have the 0 index.
Yo must check if the list contain something before accessing any item inside:
if row:
print(row[0])
As I said in comment, your solution is flawed, because it will overflow the stack at some point. You should use an infinite loop instead of calling the main function again and again
def main():
while 1:
userCom = input("\nCommand: ")
if userCom == "list":
lists()
elif userCom == "view":
count()
elif userCom == "add":
add()
elif userCom == "del":
delete()
elif userCom == "exit":
exitt()
else:
print("Invaild input, try again")
# main()

Python Note script with dictionary throwing error [duplicate]

This question already has answers here:
input() error - NameError: name '...' is not defined
(15 answers)
Closed 5 years ago.
python 2.7.9 so i wanted to make a script to run constantly where i can take notes on names and characteristics but i don't know why its throwing this error. eventually i would like it to be exported to a file so it can save the inputted information.
Traceback (most recent call last):
File "C:\Users\Admin\Desktop\PythonFiles\Dictionary.py", line 18, in
key = input("Enter a player name: ")
File "", line 1, in
Name Error: name 'bob' is not defined
basket = {}
print("""
Note Program:
___________
1: Add Item
2: Remove Item
3: View
0: Exit Program
""")
option = int(input("Enter an Option: "))
while option != 0:
if option == 1:
key = input("Enter a player name: ")
if key in basket:
print("Name Found!...")
value = input("adding notes: ")
basket[key] += value
else:
value = input("Notes: ")
basket[key] = value
elif option == 2:
key = input("Enter a player name: ")
del(basket[key])
elif option == 3:
for key in basket:
print(key,":",basket[key])
elif option !=0:
print("please enter a valid option")
option = str(input("\n\nEnter an option: "))
else:
print("Note Program Closed.")
You should use raw_input() instead of input(), as input is trying to eval() which is causing the exception.
raw_input() takes the input and passes it back as a string.
input() will actually run as eval(raw_input()).

How do I make my code add new inputs on a new line in a document while using the .writelines in python?

So I have a file which I have to use this code in order to write in it.
It needs to be able to do so in a way that adds all new inputs in one iteration on a new line of the text document. I tried to see if this would be done automatically every time I run an instance of my code but the only thing that happens is that the information that I previously put in was replaced by the new info.
membership_data = open("C:\\Users\\user\Desktop\Pre-release\membership_data.txt", "w")
def ValidateMemberID(MemberID):
if len(MemberID) !=6:
return("Wrong Format")
elif MemberID[:1] == (MemberID[:1]).lower():
return("Wrong Format")
elif MemberID[1:3] == (MemberID[1:3]).upper():
return("Wrong Format")
elif (MemberID[3:]).isdigit() == False:
return("Wrong Format")
else:
return("Correct Format")
Name = input("Please input member name")
MemberID = input("Please input member ID")
ValidateMemberID(MemberID)
if ValidateMemberID(MemberID) == "Correct Format":
NameID = [Name, MemberID]
else:
print ("Invalid MemberID")
membership_data.writelines(NameID)
membership_data.close()
input()
My issue springs up here as I'm not sure what to do.
Name = input("Please input member name")
MemberID = input("Please input member ID")
ValidateMemberID(MemberID)
if ValidateMemberID(MemberID) == "Correct Format":
NameID = [Name, MemberID]
else:
print ("Invalid MemberID")
membership_data.writelines(NameID)
membership_data.close()
My end result is such that I will have any number of records that I can easily add to (which I will organise into a table later) in this format:
Ammar Khazal Amm123
John Smith Joh456
Lily White Lil789
Simple.
membership_data = open("C:\\Users\\user\Desktop\Pre-release\membership_data.txt", "w") has the opening setting as "w", which is write, or overwrite. You just need to change the setting to "a" which is appending.
membership_data = open("C:\\Users\\user\Desktop\Pre-release\membership_data.txt", "a")
That is what you want for adding another line.

Categories

Resources