I try to create an object saving account and store it in a dictionary and this works fine but when i try to use the object of the dictionary with an method i get an error, so im not sure what im doing wrong?
I hope you guys understand what im trying to say and if somebody has an easier way to get the what i look for please let me know.
thanks
def print_accounts(accounts):
print(accounts)
pass
def add_savingaccount(account_name, iban, name, address, accounts):
print(accounts, name)
accounts[name]=account_name
account_name = SavingAccount(iban , name, address)
pass
def get_savingaccount(accounts, name):
current_account = (accounts.get(name, 'Name nicht verfügbar'))
print(current_account)
user_answer = int(input("What do you want to do 1. get credit, 2. withdraw, 3. deposit, 4. close account, 5. open account, 6. change rate, 7. sleep: "))
if user_answer == 1:
current_account.encode().decode().show_credit()
elif user_answer == 2:
current_account.withdrawn(int(input("How much do you want to withdraw: ")))
elif user_answer == 3:
current_account.deposit(int(input("How much do you want to deposit: ")))
elif user_answer == 4:
current_account.close_account()
elif user_answer == 5:
current_account.open_account()
elif user_answer == 6:
current_account.change_interest_rate(int(input("How much do you want to deposit: ")))
elif user_answer == 7:
current_account.sleep(int(input("Sleep time: ")))
pass
def load_accounts(accounts, filename):
with open(filename, "r") as file:
accounts = json.load(file)
#for key in phone_book:
# accounts[key]=phone_book[key]
accounts.update(accounts)
pass
def save_accounts(accounts, filename):
with open(filename, "w+") as new_file:
json.dump(accounts, new_file, separators=(',',':'))
pass
def print_menu():
print ('1. Print Phone Numbers')
print ('2. Add a SavingAccount')
print ('4. Get SavingAccount')
print ('5. Load accounts')
print ('6. Save accounts')
print ('7. Quit')
print()
accounts = {}
menu_choice = 0
print_menu()
while True:
menu_choice = int(input("Type in a number (1-7): "))
if menu_choice == 1:
print_accounts(accounts)
print_menu()
elif menu_choice == 2:
print("Add Name and Number (Valid IBAN gets transferred)")
account_name = input("Accountname: ")
name = input("Name: ")
iban = "CH 54 3242 3345 5342 4235"
address = input("Address: ")
add_savingaccount(account_name, iban, name, address, accounts)
print_menu()
elif menu_choice == 4:
print("get_savingaccount")
name = input("Name: ")
get_savingaccount(accounts, name)
print_menu()
elif menu_choice == 5:
filename = input("Filename to load: ")
load_accounts(accounts, filename)
print_menu()
elif menu_choice == 6:
filename = input("Filename to save: ")
save_accounts(accounts, filename)
print_menu()
elif menu_choice == 7:
break
else:
print_menu()
Related
import re
contact = {}
def display_contact():
for name, number in sorted((k,v) for k, v in contact.items()):
print(f'Name: {name}, Number: {number}')
#def display_contact():
# print("Name\t\tContact Number")
# for key in contact:
# print("{}\t\t{}".format(key,contact.get(key)))
while True:
choice = int(input(" 1. Add new contact \n 2. Search contact \n 3. Display contact\n 4. Edit contact \n 5. Delete contact \n 6. Save your contact as a file \n 7. Update Saved List \n 8. Exit \n Your choice: "))
if choice == 1:
while True:
name = input("Enter the contact name ")
if re.fullmatch(r'[a-zA-Z]+', name):
break
while True:
try:
phone = int(input("Enter number "))
except ValueError:
print("Sorry you can only enter a phone number")
continue
else:
break
contact[name] = phone
elif choice == 2:
search_name = input("Enter contact name ")
if search_name in contact:
print(search_name, "'s contact number is ", contact[search_name])
else:
print("Name is not found in contact book")
elif choice == 3:
if not contact:
print("Empty Phonebook")
else:
display_contact()
elif choice == 4:
edit_contact = input("Enter the contact to be edited ")
if edit_contact in contact:
phone = input("Enter number")
contact[edit_contact]=phone
print("Contact Updated")
display_contact()
else:
print("Name is not found in contact book")
elif choice == 5:
del_contact = input("Enter the contact to be deleted ")
if del_contact in contact:
confirm = input("Do you want to delete this contact Yes or No? ")
if confirm == 'Yes' or confirm == 'yes':
contact.pop(del_contact)
display_contact
else:
print("Name is not found in phone book")
elif choice == 6:
confirm = input("Do you want to save your contact-book Yes or No?")
if confirm == 'Yes' or confirm == 'yes':
with open('contact_list.txt','w') as file:
file.write(str(contact))
print("Your contact-book is saved!")
else:
print("Your contact book was not saved.")
# else:
elif choice == 7:
confirm = input("Do you want to update your saved contact-book Yes or No?")
if confirm == 'Yes' or confirm == 'yes':
with open('contact_list.txt','a') as file:
file.write(str(contact))
print("Your contact-book has been updated!")
else:
print("Your contact book was not updated.")
else:
break
I add to if else function, one to save the contact list and one to just update it with the new contact. But When I run it I still get the old contact that where already saved. Any ideas on how to fix it to only append the new contacts to the already saved txt file.
elif choice == 6:
confirm = input("Do you want to save your contact-book Yes or No?")
if confirm == 'Yes' or confirm == 'yes':
with open('contact_list.txt','w') as file:
file.write(str(contact))
print("Your contact-book is saved!")
else:
print("Your contact book was not saved.")
# else:
elif choice == 7:
confirm = input("Do you want to update your saved contact-book Yes or No?")
if confirm == 'Yes' or confirm == 'yes':
with open('contact_list.txt','a') as file:
file.write(str(contact))
print("Your contact-book has been updated!")
else:
print("Your contact book was not updated.")
I just changed the "w" in choice 7 to "a" to append the new contact but I still get all the old one in the new save. Any ideas.
I have made two functions to update any value of a student's record. When I'm updating the rollno, class or any of the marks, the programme works great but every time I try to update the name it gives the following error:
1054 (42S22): Unknown column 'colum_name' in 'field list'
Both of the functions are perfectly correct I think because everything except name updates fine.
The two functions are:
def update(_class, _rollno):
"""
Takes in the class and roll non as arguments
and updates the details of a single student.
"""
print(
"\n-----Enter what you want to update-----\n"
"\n1) Class"
"\n2) Roll no."
"\n3) Name"
"\n4) Maths Marks"
"\n5) Physics Marks"
"\n6) Chemistry Marks"
"\n7) English Marks"
"\n8) Computer science Marks"
"\n9) Exit the update section"
)
choice = input('\nEnter your choice - ')
if not choice.isnumeric():
print("\nPlz check your input and try again.....")
update(_class, _rollno)
elif int(choice) == 1:
nclass = input("Enter the new class of the student = ")
_update(nclass, "class", _class, _rollno)
update(nclass, _rollno)
elif int(choice) == 2:
nrollno = input("Enter the new rollno of the student = ")
_update(nrollno, "roll_no", _class, _rollno)
update(_class, nrollno)
elif int(choice) == 3:
nname = input("Enter the new name of the student = ")
_update(nname, "student_name", _class, _rollno)
update(_class, _rollno)
elif int(choice) == 4:
nmaths = input("Enter the new math marks of the student = ")
_update(nmaths, "math_marks", _class, _rollno)
update(_class, _rollno)
elif int(choice) == 5:
nphy = input("Enter the new phy marks of the student = ")
_update(nphy, "phy_marks", _class, _rollno)
update(_class, _rollno)
elif int(choice) == 6:
nchem = input("Enter the new chem marks of the student = ")
_update(nchem, "chem_marks", _class, _rollno)
update(_class, _rollno)
elif int(choice) == 7:
neng = input("Enter the new eng marks of the student = ")
_update(neng, "eng_marks", _class, _rollno)
update(_class, _rollno)
elif int(choice) == 8:
ncs = input("Enter the new cs marks of the student = ")
_update(ncs, "comp_marks", _class, _rollno)
update(_class, _rollno)
elif int(choice) == 9:
start()
def _update(new, value, _class, _rollno):
"""
Takes in the updated value, name of value, class
and roll no. of the students and updates the value.
"""
flag = 0
try:
qry = "update students set " + value + " = " + new + \
" WHERE class = " + _class + " and roll_no = " + _rollno
execute(qry)
mydb.commit()
if cursor.rowcount == 1:
print("\nData updated successfully.")
else:
print("\nValue not found. Please check if this is present in database.")
except Exception as e:
print("\n",e)
flag = 1
if flag != 0:
print("\nOops!!! Something went wrong. "
"Please check your input data and try again.")
You can find the entire code here:
https://github.com/Hrshl-Gunjal/Class_12_Python_Mysql_CBSE_Project
Can anyone please help me in finding the solution to this problem ???
I am having trouble writing a program to repeat input part. for instance
input 1 ___run add_contact()
again ask for input
input 4____run disp_contact()
...
...
I've never written a long code! :\
I'm totally begginer! and learning a bit of Python in my spare time
my mentor said you should define several functions and put them in a main function which get input.
so If anyone can tell me why I get stuck like this I would appreciate it.
contact={}
print(''' phone book
1. add contact
2.delete contact
3.search contact
4.display all
5.Quit''')
def add_contact():
name=input('enter the name: ')
number=input('enter the number: ')
contact[name]=number
print(name, 'added to phone book!')
def del_contact():
name=input('enter the name: ')
while name not in contact:
print("not found! try again" )
name=input('enter again: ')
else:
print(name,' deleted')
del contact[name]
name=False
def search_contact():
name=input('enter the name: ')
while name not in contact:
print('not found!')
name=input('enter again: ')
else:
print(name, 'number is :', contact[name])
def disp_contact():
if len(contact)>0:
print('phone book contacts are: ')
for i in contact:
print(i, end=' ')
else:
print('phone book is empty!')
def main_def(num):
if num==1:
add_contact()
elif num==2:
del_contact()
elif num==3:
search_contact()
elif num==4:
disp_contact()
elif num==5:
print('bye bye')
x=int(input(' enter a number: '))
main_def(x)
You may wrap the main_def in a while True, and use exit(O) to quit properly when 5 is given
def main_def(num):
if num == 1:
add_contact()
elif num == 2:
del_contact()
elif num == 3:
search_contact()
elif num == 4:
disp_contact()
elif num == 5:
exit(0)
while True:
x = int(input(' enter a number: '))
main_def(x)
Note
For del_contact and search_contact, you don't need the else just put after like this
def del_contact():
name = input('enter the name: ')
while name not in contact:
print("not found! try again")
name = input('enter again: ')
print(name, ' deleted')
del contact[name]
I am currently learning Python and I am making a tennis coach program. On the option 3 where you can update it is not working as it says nameUnder is not defined in the else statement. Please help as I really don't understand why its not working. I have also tries it without the split but that to doesn't work
import os, sys
print("Please select an option:")
print("[1] Add a student")
print("[2] Read a students data")
print("[3] Update a students data")
print("[4] Delete a students data")
menuSelect = int(input("Make your number selection: "))
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if menuSelect == 1:
amountDone=0
amounttodo=int(input("Enter the number of contestants you would like to add: "))
while amounttodo>amountDone:
ageOne=int(input("Enter the age of the contestant: "))
if ageOne <= 11:
underFile=open("Under11s.txt","a")
nameUnder=input("Enter the first name of the student: ")
genderUnder=input("Enter the gender of the student: ")
posUnder=int(input("Input the last position of the student: "))
underFile.write("\n"+str(nameUnder) + " | " + str(genderUnder) + " | " + str(posUnder))
underFile.close()
amountDone=amountDone+1
elif ageOne >= 12:
overFile=open("Over11s.txt","a")
nameOver=input("Enter the first name of the student: ")
genderOver=input("Enter the gender of the student: ")
posOver=int(input("Input the last position of the student: "))
overFile.write("\n"+str(nameOver) + " | " + str(genderOver) + " | " + str(posOver))
overFile.close()
amountDone=amountDone+1
else:
print("Invalid, Please enter a number")
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
elif menuSelect == 2:
print("Enter the file you would like to open.")
print("1) Under 11's")
print("2) Over 11's")
fileToOpen=int(input("Enter the number of your selection: "))
if fileToOpen == 1:
f = open("Under11s.txt", "r")
file_contents = f.read()
print(file_contents)
elif fileToOpen == 2:
f = open("Over11s.txt", "r")
file_contents = f.read()
print(file_contents)
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
elif menuSelect == 3:
studentName = input("Enter the student name you are looking for:")
file = open("Under11s.txt","r")
found=False
for line in file:
details = line.split(",")
writefile = open("Under11supdated.txt","a")
details = line.split(",")
if details[0] == studentName:
found=True
nameUnder=input("Enter the first name of the student: ")
genderUnder=input("Enter the gender of the student: ")
posUnder=int(input("Input the last position of the student: "))
file.write("\n"+str(nameUnder)[0] + " | " + str(genderUnder)[1] + " | " + str(posUnder)[2])
else:
file.write("\n"+nameUnder[0] + " | " + genderUnder[1] + " | " + posUnder[2])
file.close()
file.close()
os.remove("Under11s.txt")
os.rename("Under11supdated.txt","Under11s.txt")
if found==True:
print("Details updated")
else:
print("That student cannot be found in the file, no changes made")
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
else:
print("Sorry, this option is not available yet!")
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
nameUnder only gets defined if this statement is true if details[0] == studentName:
Not a 100% of your logic here, but make sure to set nameUnder= "" before the if statement so the variable is declared and can be used in your else clause.
I would recommend you to structure your code with functions for the each options etc., will make it easier to read and possible reuse some of the code.
Partly updated code:
writefile = open("Under11supdated.txt","a")
details = line.split(",")
nameUnder = ""
if details[0] == studentName:
found=True
nameUnder=input("Enter the first name of the student: ")
genderUnder=input("Enter the gender of the student: ")
When running a code to log in to a system with a username and password I get the error 'secret' is not defined, how can I get it to stop saying that and to run normally?
This is the error message:
Traceback (most recent call last):
File "C:\Users\Samuel\Documents\School\Computing\NEA - H\Program.py", line 16, in
while username != secret:
NameError: name 'secret' is not defined
This is the code:
from random import randint
import os
import time
import sys
#xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
username = ""
while username != secret:
username = input("Please enter the username: ")
if username == secret:
print("Thank you. You have entered the correct username")
else:
print("Sorry the value entered in incorrect - try again")
password = ""
while password != password:
password = input("Please enter the password: ")
if password == password:
print("Thank you. You have entered the correct password, You are now in the menu system")
else:
print("Sorry the value entered in incorrect - try again")
def online():
time.sleep(1)
print("Welcome Teacher")
logIn()
#xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
def addStudent():
print("Loading student creator...")
time.sleep(1)
studentFile = open("Student_Details.txt","w")
ID = randint(1,1000)
surname = input("Surname: ")
time.sleep(1)
forename = input("Forename: ")
time.sleep(1)
DOB = input("Date of Birth: ")
time.sleep(1)
age = input("Age: ")
time.sleep(1)
homeAddress = input("Home address: ")
time.sleep(1)
homePhone = input("Home phone number: ")
time.sleep(1)
gender = input("Gender: ")
time.sleep(1)
tutor = randint(1,48)
time.sleep(1)
print("Writing to 'Student details.txt' now")
time.sleep(1.5)
email = (forename + surname + str(ID) + "#treeroadschool.net")
studentFile.write(str(ID) + "\n")
studentFile.write(surname + "\n")
studentFile.write(forename + "\n")
studentFile.write(str(DOB) + "\n")
studentFile.write(str(age) + "\n")
studentFile.write(homeAddress + "\n")
studentFile.write(homePhone + "\n")
studentFile.write(gender + "\n")
studentFile.write(str(tutor) + "\n")
studentFile.write(email + "\n")
studentFile.close()
print("Student data stored")
#xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
def logOut():
print("Logging out...")
sys.exit()
#xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
def viewStudent():
print("MENU")
print("Choose one of the students by their number:")
print("><><><><><><><><><><><><><><><><><><><><><")
time.sleep(1)
print("1-25")
time.sleep(1)
choice2 = int(input("Choice? "))
print("><><><><><><><><><><><><><><><><><><><><><")
time.sleep(1)
if choice2 == 1:
studentFile1 = open('Student_Details_01.txt', 'r')
print (studentFile1.readlines())
elif choice2 == 2:
studentFile2 = open('Student_Details_02.txt', 'r')
print (studentFile2.readlines())
elif choice2 == 3:
studentFile3 = open('Student_Details_03.txt', 'r')
print (studentFile3.readlines())
elif choice2 == 4:
studentFile4 = open('Student_Details_04.txt', 'r')
print (studentFile4.readlines())
elif choice2 == 5:
studentFile5 = open('Student_Details_05.txt', 'r')
print (studentFile5.readlines())
elif choice2 == 6:
studentFile6 = open('Student_Details_06.txt', 'r')
print (studentFile6.readlines())
elif choice2 == 7:
studentFile7 = open('Student_Details_07.txt', 'r')
print (studentFile7.readlines())
elif choice2 == 8:
studentFile8 = open('Student_Details_08.txt', 'r')
print (studentFile8.readlines())
elif choice2 == 9:
studentFile9 = open('Student_Details_09.txt', 'r')
print (studentFile9.readlines())
elif choice2 == 10:
studentFile10 = open('Student_Details_10.txt', 'r')
print (studentFile10.readlines())
elif choice2 == 11:
studentFile11 = open('Student_Details_11.txt', 'r')
print (studentFile11.readlines())
elif choice2 == 12:
studentFile12 = open('Student_Details_12.txt', 'r')
print (studentFile12.readlines())
elif choice2 == 13:
studentFile13 = open('Student_Details_13.txt', 'r')
print (studentFile13.readlines())
elif choice2 == 14:
studentFile14 = open('Student_Details_14.txt', 'r')
print (studentFile14.readlines())
elif choice2 == 15:
studentFile15 = open('Student_Details_15.txt', 'r')
print (studentFile15.readlines())
elif choice2 == 16:
studentFile16 = open('Student_Details_16.txt', 'r')
print (studentFile16.readlines())
elif choice2 == 17:
studentFile17 = open('Student_Details_17.txt', 'r')
print (studentFile17.readlines())
elif choice2 == 18:
studentFile18 = open('Student_Details_18.txt', 'r')
print (studentFile18.readlines())
elif choice2 == 19:
studentFile19 = open('Student_Details_19.txt', 'r')
print (studentFile19.readlines())
elif choice2 == 20:
studentFile20 = open('Student_Details_20.txt', 'r')
print (studentFile20.readlines())
elif choice2 == 21:
studentFile21 = open('Student_Details_21.txt', 'r')
print (studentFile21.readlines())
elif choice2 == 22:
studentFile22 = open('Student_Details_22.txt', 'r')
print (studentFile22.readlines())
elif choice2 == 23:
studentFile23 = open('Student_Details_23.txt', 'r')
print (studentFile23.readlines())
elif choice2 == 24:
studentFile24 = open('Student_Details_24.txt', 'r')
print (studentFile24.readlines())
elif choice2 == 25:
studentFile25 = open('Student_Details_25.txt', 'r')
print (studentFile25.readlines())
else:
sys.exit()
#xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
def viewReport():
print("Loading Report...")
time.sleep(1)
studentFileReport = open('Student_Details_Report.txt', 'r')
print (studentFileReport.readlines())
#xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
time.sleep(1)
print("><><><><><><><><><><><><><><><><><><><><><")
print("MENU")
print("Choose one of the options by their number:")
print("><><><><><><><><><><><><><><><><><><><><><")
time.sleep(1)
print("1: Add student")
print("2: Log out")
print("3: View student")
print("4: View report")
time.sleep(1)
choice = int(input("Choice? "))
print("><><><><><><><><><><><><><><><><><><><><><")
time.sleep(1)
if choice == 1:
addStudent()
elif choice == 2:
logOut()
elif choice == 3:
viewStudent()
elif choice == 4:
viewReport()
else:
sys.exit()