I can't break the while loop - python

import re
#list of user information
list_id = []
list_name = []
list_surname = []
list_age = []
list_nationalid = []
list_mail = []
class Record:
def __init__(self,programName):
self.programName = programName
self.loop = True
print("welcome {}.".format(programName))
def program(self):
while True: #the loop gonna keep ask if input is not a correct number
try:
userInput = int(input ("what you want to do?\n1-addRecord\n2-removeRecord\n3-listRecord\n4-exitRecord\n"))
if userInput < 5 and userInput > 0:
self.menu(userInput)
break
else:
print("pls enter a valid number")
except Exception :
print("pls enter a valid number again ")
def menu(self,userInput):
self.userInput = userInput
if userInput == 1:
print("addRecord is opening")
self.addRecord()
if userInput == 2:
print("removeRecord is opening")
self.removeRecord()
if userInput == 3:
print("list Record are opening")
self.listRecord()
if userInput == 4:
self.exitRecord()
def addRecord(self):
while True:
user_name = input("pls enter your name")
if user_name == re.findall("[^a-z]"):
list_name.append(user_name)
print ("addRecord_name worked")
break
else:
print ("enter a valid name")
while True:
user_surname = input("pls enter your name")
if user_surname == re.findall("[^a-zA-E]"):
list_surname.append(user_surname)
print ("addRecord_surname worked")
break
else:
print ("enter a valid surname")
while True:
user_age = input("pls enter your age")
if user_age == re.findall("[^0-9]"):
list_age.append(user_age)
print ("addRecord_age worked")
break
else:
print ("enter a valid age")
while True:
user_nationalid = input("pls enter your national id")
if user_name == re.findall("[^0-9]"):
list_nationalid.append(user_nationalid)
print ("addRecord_nationalid worked")
break
else:
print ("enter a valid national id")
while True:
user_mail = input("pls enter your name")
if user_name == re.search("#" and ".com" , user_mail):
list_mail.append(user_mail)
print ("addRecord_mail worked")
break
else:
print ("enter a valid national id")
def removeRecord(self):
pass
def listRecord(self):
pass
def backToMenu(self):
pass
def exitRecord(self):
pass
System = Record("admin")
System.program() #its for keep working `program`
I trying to make a program which is add/remove/list data. the while loop which is in program is not breaking. even If I enter my name at addRecord function it prints "pls enter a valid number again ". problem is not about addRecord function because I already have that problem before I write these function. any advice or explain ?

Here is the corrected code, however your implementation of the menu is still not the best practices.
import re
list_id = []
list_name = []
list_surname = []
list_age = []
list_nationalid = []
list_mail = []
class Record:
def __init__(self,programName):
self.programName = programName
self.loop = True
print("welcome {}.".format(programName))
def program(self):
while True: #the loop gonna keep ask if input is not a correct number
try:
userInput = int(input ("what you want to do?\n1-addRecord\n2-removeRecord\n3-listRecord\n4-exitRecord\n"))
if userInput < 5 and userInput > 0:
self.menu(userInput)
else:
print("pls enter a valid number")
except Exception :
print("pls enter a valid number again ")
def menu(self,userInput):
self.userInput = userInput
if userInput == 1:
print("addRecord is opening")
self.addRecord()
if userInput == 2:
print("removeRecord is opening")
self.removeRecord()
if userInput == 3:
print("list Record are opening")
self.listRecord()
if userInput == 4:
self.exitRecord()
def addRecord(self):
while True:
user_name = input("pls enter your name")
if re.findall("[^a-z]", user_name) == []:
list_name.append(user_name)
print ("addRecord_name worked")
break
else:
print("enter a valid name")
while True:
user_surname = input("pls enter your surname")
if re.findall("[^a-zA-E]", user_surname) == []:
list_surname.append(user_surname)
print ("addRecord_surname worked")
break
else:
print("enter a valid surname")
while True:
user_age = input("pls enter your age")
if re.findall("[^0-9]", user_age) == []:
list_age.append(user_age)
print ("addRecord_age worked")
break
else:
print("enter a valid age")
while True:
user_nationalid = input("pls enter your national id")
if re.findall("[^0-9]", user_nationalid) == []:
list_nationalid.append(user_nationalid)
print ("addRecord_nationalid worked")
break
else:
print("enter a valid national id")
while True:
user_mail = input("pls enter your email")
if re.search("#" and ".com" , user_mail):
list_mail.append(user_mail)
print ("addRecord_mail worked")
break
else:
print ("enter a valid email")
def removeRecord(self):
pass
def listRecord(self):
pass
def backToMenu(self):
pass
def exitRecord(self):
pass
System = Record("admin")
System.program() #its for keep working `program`

Related

How to import login/registration database in second part of code?

I have written 2 pieces of code.
login and authentication
def register():
db = open("database.txt","r")
account_number= input("Enter your Account Number: ")
pin = input("Create a 4-digit pin: ")
pin1 = input("Confirm Pin: ")
d = []
f = []
for i in db:
a,b = i.split(", ")
b = b.strip()
d.append(a)
f.append(b)
data = dict(zip(d,f))
print(data)
if pin != pin1:
print("Pins don't match, try again!")
register()
else:
if len(pin) != 4:
print("Pin is not 4-digit. Pin must be 4-digit")
register()
elif account_number in d:
print("account number already exists")
register()
else:
db = open("database.txt","a")
db.write(account_number+", "+pin+", 0" "\n")
print("Success!")
db.close()
def access():
db = open("database.txt", "r")
account_number = input("Enter your account number: ")
pin = input("Enter your pin: ")
if not len(account_number or pin)<1:
d = []
f = []
for i in db:
a, b = i.split(", ")
b = b.strip()
d.append(a)
f.append(b)
data = dict(zip(d, f))
try:
if data[account_number]:
try:
if pin== data[account_number]:
print("Login Success")
else:
print("Pin or Account Number Incorrect")
except:
print("Pin or Account Number Incorrect")
else:
print("Account Number doesn't exist")
except:
print("Login error")
else:
print("Please Enter your login credentials")
db.close()
def home(option = None):
option = input("Login | Signup: ")
if option == "Login":
access()
elif option == "Signup":
register()
else:
print("Please choose an option")
home()
money transactions
choice = 0
while choice != 4:
print("\n\n**** Menu *****")
print("1 -- balance")
print("2 == deposit")
print("3 == withdraw")
print("4 == cancel\n")
choice=int(input("\nEnter your option:\n"))
if choice==1:
print("Balance = ", +balance)
elif choice==2:
dep=int(input("Enter your deposit: "))
balance+=dep
print("\n deposited amount: " , +dep)
print("balance = ", +balance)
elif choice==3:
wit=int(input("Enter the amount to withdraw: "))
balance -= wit
print("\n withdrawn amount: " , +wit)
print("balance =", +balance)
elif choice ==4:
print('Session ended,goodbye.')
else:
print("Invalid Entry")
The first code stores an account number and pin in the database. The second code should use the balance from the database and perform the transactions. After performing the transactions it should update the database. How can I import the database made in the first code to be used in the second code?

key error problem ,when enter "aa" in lendfuction (in book name)

it is showing an error when i enter "aa"(without quotes in lend_book function in book name ).
class library:
def __init__(self,list,library_name):
self.listofbook = list
self.library_name = library_name
self.lendbook = {}
self.Ldict = {}
def display_book(self):
for book in self.listofbook:
if book not in self.Ldict:
print(book)
def lend_book(self):
name_book1 = input('Enter the book you lend\n>')
name_ur1 = input('Enter your name\n>')
bdict = {name_book1:name_ur1}
if name_book1 in self.listofbook:
self.Ldict.update(bdict)
self.listofbook.remove(name_book1)
print("book has been issue to you")
else:
print(f"{name_book1} was not available\n{self.Ldict[name_book1]} currently owns the book")
def donate_book(self):
print("Enter the name or list of book that you wants to donate\n>")
donate_book = input()
self.listofbook.extend(donate_book)
def return_book(self):
name_book2 = input('Enter the book you want to return\n>')
name_ur2 = input('Enter your name\n>')
bdict2 = {name_book2:name_ur2}
del self.Ldict[name_book2]
self.listofbook.extend(name_book2)
def addBook(self):
book = input()
self.listofbook.append(book)
print("Book has been added to the book list")
def printLend(self):
if self.Ldict=={}:
print("No book is lended")
else:
print('those who lend books')
for key in self.Ldict:
print(f'Book {key} and Name {self.Ldict[key]}')
def Option(self,a):
if a==1:
return self.display_book()
elif a==2:
return self.lend_book()
elif a==3:
return self.donate_book()
elif a==4:
return self.return_book()
elif a==5:
return self.printLend()
elif a==6:
return self.addBook()
else:
print("Enter a vaild option")
if __name__=='__main__':
sumit = library(["jungalbook","thatbook","a","b","c","d"],"sumit_library")
while True:
print(f"Welcome to the {sumit.library_name}")
print("Enter options to continue")
print("1-display book")
print("2-lend book")
print("3-donate book")
print("4-return book")
print("5-details for books were lended")
print("6-Add book")
op = int(input())
sumit.Option(op)
print("Press 'q' to quit and 'c' to continue")
user_choice2 = ''
while(user_choice2!="c" and user_choice2!="q"):
user_choice2 = input()
if user_choice2 == "q":
exit()
elif user_choice2 == "c":
continue
please help

Python Coursework tidying

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()

I am coding a calculator and need help allowing user inputs to be floats

Okay, this is my code, it is in python 3.4.3 and I do not know how I would go about allowing user inputs to be floats. Any help would be greatly appreciated.
It is a calculator and works perfectly but it does not allow user inputs to be floats(have decimal places) and a lot of calculations take place with inputs of decimal numbers so it kinda needs it. Thanks if you take the time to read that!
import time
def cls(): print ("\n"*100)
def add():
cls()
print("you have selected addition")
a = input("Enter your first number: ")
while a.isdigit() == False:
print("Enter a numerical interger")
a = input("Enter your first number: ")
if a.isdigit() == True:
a = int(a)
b = input("Enter your second number: ")
while b.isdigit() == False:
print("Enter a numberical interger")
b = input ("enter your second number: ")
if b.isdigit() == True:
b = int(b)
print ("\n")
print ("ANSWER:",a,"+",b,"=",a+b)
print ("\n")
def sub():
cls()
print("you have selected subtraction")
a = input("Enter your first number: ")
while a.isdigit() == False:
print("Enter a numerical interger")
a = input("Enter your first number: ")
if a.isdigit() == True:
a = int(a)
b = input("Enter your second number: ")
while b.isdigit() == False:
print("enter a numerical interger")
b = input("Enter your second number: ")
if b.isdigit() == True:
b = int(b)
print("\n")
print ("ANSWER:",a,"-",b,"=",a-b)
print("\n")
def multi():
cls()
print ("you have selected multiplication")
a = input("Enter your first number: ")
while a.isdigit() == False:
print("Enter a numerical interger")
a = input("Enter your first number: ")
if a.isdigit() == True:
a = int(a)
b = input("Enter your second number: ")
while b.isdigit() == False:
print("enter a numerical interger")
b = input("Enter your second number: ")
if b.isdigit() == True:
b = int(b)
print("\n")
print("ANSWER:",a,"*",b,"=",a*b)
print("\n")
def divide():
cls()
print ("you have selected division")
a = input("Enter your first number: ")
while a.isdigit() == False:
print("Enter a numerical interger")
a = input("Enter your first number: ")
if a.isdigit() == True:
a = int(a)
b = input("Enter your second number: ")
while b.isdigit() == False:
print("enter a numerical interger")
b = input("Enter your second number: ")
if b.isdigit() == True:
b = int(b)
c = (a/b)
if a%b ==0 :
print("\n")
print ("ANSWER:",a,"/",b,"=",int(c))
print("\n")
else :
print("\n")
print ("ANSWER:",a,"/",b,"=",float(c))
print("\n")
def indice():
cls()
print ("you have selected indice multiplication")
a = input("Enter your first number: ")
while a.isdigit() == False:
print("Enter a numerical interger")
a = input("Enter your first number: ")
while (int(a)) >=1000000000000:
print("value too high, enter a lower value")
time.sleep(1)
a = input("Enter your first number: ")
if a.isdigit() == True:
a = int(a)
b = input("Enter your second number: ")
while b.isdigit() == False:
print("enter a numerical interger")
b = input("Enter your second number: ")
while (int(b)) >=1000:
print("value too high, enter a lower value")
time.sleep(1)
b = input("Enter your second number: ")
if b.isdigit() == True:
b = int(b)
print("\n")
print("ANSWER:",a,"To the power of",b,"=",a**b)
print("\n")
def Tconv():
cls()
print("You have selected unit conversion")
print("\n")
print("Enter 1 for conversion from celcius")
print("Enter 2 for conversion from kelvin")
print("\n")
a = input("Enter your choice: ")
if a == "1":
cls()
Tcelc()
elif a == "2":
cls()
Tkelv()
else:
print("Not a valid entry, try again")
time.sleep(1)
cls()
Tconv()
def Tcelc():
print("You have selected conversion from celcius")
print("\n")
a = input("Enter your celcius value: ")
if a.isdigit() == False:
print("Not a valid entry")
time.sleep(1)
cls()
Tcelc()
elif a.isdigit() == True:
print("\n")
print("AWNSER = ",(int(a))+273,"Kelvin")
print("\n")
def Tkelv():
print("You have selected conversion from kelvin")
print("\n")
a = input("Enter your kelvin value: ")
if a.isdigit() == False:
print("Not a valid entry")
time.sleep(1)
Tkelv()
elif a.isdigit() == True:
print("ANSWER = ",(int(a))-273,"Celcius")
print("\n")
def OpEx():
cls()
print("what operation would you like to preform?")
print("\n")
print("Enter 1 for addition")
print("Enter 2 for subtraction")
print("Enter 3 for multliplication")
print("Enter 4 for division")
print("Enter 5 for indice multiplication")
print("Enter 6 for unit conversion")
print("\n")
print("Or type 'close' to exit the program")
print("\n")
task = input("enter your choice: ")
print("\n")
if task == "1":
add()
menu()
elif task == "2":
sub()
menu()
elif task == "3":
multi()
menu()
elif task == "4":
divide()
menu()
elif task == "5":
indice()
menu()
elif task == "6":
Tconv()
menu()
elif task == "close":
exit()
else:
print ("not a valid entry")
time.sleep(2)
OpEx()
def menu():
Q1 = input("Type 'yes' to preform a calculation type 'no' to exit: ")
if Q1 == "yes":
OpEx()
if Q1 == "no":
print("sorry I could not be of futher service")
time.sleep(1)
exit()
else:
print("\n")
print("Not a valid entry, try again")
print("\n")
time.sleep(1)
cls()
menu()
cls()
menu()
You're converting user input to integers, which don't handle floating point all that well. Try converting to float instead, e.g.:
a = float(a)
I would be cautious taking the input as a float because python and many other languages floats are not represented as they may seem. I would recommend pulling the input as a string and then casting it later.

Invalid syntax error on the elif statement

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()

Categories