im trynig to operate a class after it has being in a dictionary and its not working.
I'm trying to operate "balance_check_in_the_bank_account" metoud at the third "if()"
when the user ask for number "2" action.
all_bank_accounts = {}
class BankAccount():
def __init__(self, first_name, last_name, personal_number,currency, amount = 0):
self.first_name = first_name
self.last_name = last_name
self.personal_number = personal_number
self.currency = currency
self.amount = amount
def balance_check_in_the_bank_account(self):
print('The amount of money in the bank is:\n ', self.amount)
while True:
cmd = int(input(" Press 1 to create a bank account or Press 2 to other options:\n"))
if cmd == 1:
first_namee = input("What is your first name? ")
last_namee = input("What is your last name? ")
personal_numberr = input("What is your ID? ")
currencyy = input("What type of currncey would you like to use? ")
amountt = int(input("What is the amount of money would you like to deposit? "))
the_account = BankAccount(first_namee, last_namee, personal_numberr, currencyy, amountt)
dictank = {f"{personal_numberr}":the_account}
all_bank_accounts.update(dictank)
print(all_bank_accounts)
else:
personal_number = input("What is your ID? ")
if personal_number in all_bank_accounts.keys():
cmd = int(input(" Press 2 to check in the bank account.\n Press 3 to deposit cash.\n Press 4 to withrawal cash.\n Press 5 to check the average of deposits or withrawals.\n Press 6 to print an account details page ."))
if cmd == 2:
one_of_the_accounts = all_bank_accounts[f"{personal_numberr}"]
one_of_the_accounts.balance_check_in_the_bank_account
else:
print("The bank account not exist")
Related
In my class called Commands, I have a "carstuff" command (it's a very basic command system) which is supposed to bring up my help menu, but instead it just brings up the python help menu. Here's my commands.py file:
class Commands:
pass
def askCommand(self):
command = input("Enter command: ")
if command == "carstuff":
#the other part that's having problems
help()
elif command == "sell":
pass
elif command == "addcar":
pass
#part that's having problems
def help(self):
print(
"carstuff: Brings up the help menu\nsell: Sells the current car\naddcar: Adds another car"
)
And here's my main.py file (I'm making a mockup of craigslist)
from car import Car
from commands import Commands
print("Welcome to Craigslist on the command line! Start by entering your car info below.")
brand = input("Enter your car brand: ")
model = input("Enter your car model: ")
year = input("Enter your car's year: ")
condition = input("Enter your car's condition: ")
car = Car(brand, model, year, condition)
print("Your car's price is: " + str(car.price))
print("Now that you've listed your car, you can use commands now!\n")
command = Commands.askCommand(Commands)
And I have another car.py file (but I don't know if it will be of any use)
class Car:
def __init__(self, brand, model, year, condition):
self.brand = brand
self.model = model
self.year = year
self.condition = condition
self.price = len(model) * 0.75 * 3000
if self.condition == "Bad":
self.price - 100
elif self.condition == "Brand New":
self.price + 100
def Sell(self):
sure = input("Are you sure you want to sell? (Y/N): ")
if sure == "Y" or "y":
self.sellprice = self.price % 75
print("You got " + self.sellprice + " from this car.")
elif sure == "N" or "n":
print("Sell cancelled.\n")
I'm trying to make a simple library where the user can add and remove books from his shopping cart, but I don't know how to use if statements with OOP and classes.
try:
class library:
def __init__(self, books, customer):
self.books = books
self.customer = customer
# sign:
check = input("manager account(1), customer account(2): ")
if check == "2":
#age >= 18
age = int(input("enter your age: "))
if age >= 18:
#name
name = input("enter your firstname: ")
# ID
import random
x = "ID"+str(random.randint(101,999))
print(f"your ID is: {x}")
print("you should memorize it")
y = input("enter password that has at list 8 caracterse: ")
# Password
while len(y) < 8:
y = input("enter password that has at list 8 caracterse: ")
print(f"your password is: {y}")
print("you should memorize it")
data = [x,y]
choice_1 = input("check your shopping cart(1): \nadd books to your shopping cart(2): \nremove books from your shopping cart(3): ")
if choice_1 == "1":
def __str__(self):
return f"customer {self.customer} bought those books{self.books}"
elif choice_1 == "2":
def __iadd__(self, other):
self.books.append(other)
return self
order = library(["the golsen company"],"Mr.asad")
print(order.books)
order += input("enter a book: ")
print(order.books)
except ValueError as ages:
print(ages)
I don't know if this is the right way to use the if statement with classes so if you can just give me an example to show how it's done correctly?
OK, I have rewritten your code to implement it in a more organized way. Your class "library" was not really a library at all; it is a class for "orders", and I have renamed it as such. I didn't know what you wanted for the manager account, so the manager account just assigns a fake user name without requiring a signup. I also fixed the spelling errors and the tabbing.
import random
import sys
class Order:
def __init__(self, books, customer):
self.books = books
self.customer = customer
def __iadd__(self, other):
self.books.append(other)
return self
def __isub__(self, other):
self.books.remove(other)
return self
def __str__(self):
return f"custumer {self.customer} bought those books {self.books}"
# sign in.
check = input("manager account(1),custumer account(2): ")
if check == '1':
x = 'manager'
if check == "2":
#age >= 18
age = int(input("enter your age: "))
if age < 18:
print("Sorry, you must be at least 18.")
sys.exit(0)
#name
name = input("enter your firstname: ")
# ID
x = "ID"+str(random.randint(101,999))
print(f"your ID is: {x}")
print("you should memorize it")
# Password
y = input("enter password that has at least 8 characters: ")
while len(y) < 8:
y = input("enter password that has at least 8 characters: ")
print(f"your password is: {y}")
print("you should memorize it")
# Main menu.
order = Order( [], x )
while True:
print('---')
choice_1 = input("1. check your shopping cart\n2. add books to your shopping cart\n3. remove books from your shopping cart\n4. quit: ")
if choice_1 == "1":
print( order )
elif choice_1 == "2":
order += input("enter a book: ")
elif choice_1 == "3":
book = input("enter a book: ")
if book in order.books:
order -= book
else:
print( f"{book} is not in your cart." )
elif choice_1 == "4":
break
when you said "fonction", I think you mean "function". When you make a try: block, you must also add an except: block. Also, don't put code directly in the class. Put it inside a function (a.k.a methods). I put the code starting from # sign in the __int__ method. We generally don't put methods (functions) inside other methods. So, put the __str__ and __iadd__ methods outside the __init__ method. To call it, use self.__str__() and self.__iadd__().
Here is the updated code:
try:
class library:
def __init__(self, books, customer):
self.books = books
self.customer = customer
# sign:
check = input("manager account(1), customer account(2): ")
if check == "2":
# age >= 18
age = int(input("enter your age: "))
if age >= 18:
# name
name = input("enter your firstname: ")
# ID
import random
x = "ID" + str(random.randint(101, 999))
print(f"your ID is: {x}")
print("you should memorize it")
y = input("enter password that has at list 8 caracterse: ")
# Password
while len(y) < 8:
y = input("enter password that has at list 8 caracterse: ")
print(f"your password is: {y}")
print("you should memorize it")
data = [x, y]
choice_1 = input("check your shopping cart(1): \nadd books to your shopping cart(2): ")
if choice_1 == "1":
self.__str__()
elif choice_1 == "2":
self.__iadd__()
# age < 18
elif age < 18:
print("this library is not for your age")
def __iadd__(self, other):
self.books.append(other)
return self
def __str__(self):
return f"customer {self.customer} bought those books{self.books}"
except:
pass
order = library(["the golsen company"], "Mr.asad")
print(order.books)
order += input("enter a book: ")
print(order.books)
Im trying to print the email of the student, in the while loop at the bottom im also trying to input the students email but I cannot figure how to do it correctly.
Code:
array1 = []
numstudents = int(input("How many students are in the class?: "))
for i in range (numstudents):
studentname,studentemail,dayofbrith,monthofbrith,yearofbrith = input("Enter the student name, the
student's email and the date of birth in the form 'name, email, day of birth, month of birth, year
of birth' : ").split("")
array1.append(studentname+studentemail+dayofbrith+monthofbrith+yearofbrith)
if studentname == "stop":
print("")
break
else:
print("")
print(array1)
while True:
email = input("From which student's email you want: ")
if email any in array1[0]:
print("")
print(array1[1])
students = []
numstudents = int(input('How many students are in the class?: '))
for _ in range(numstudents):
print("Please enter the following: ")
print("The student's name, The student's email, day of birth, month of birth, year of birth")
students.append(input().split())
target = input("Which studen't email you want: ")
for i in students:
if i[0] == target:
print(f"The student's email is {i[1]}")
Try if this is what you want
Ah, definitely a problem for a dictionary.
dict1= {}
numstudents = int(input("How many students are in the class?: "))
for _ in range (numstudents): #As nk03 correctly points out - we don't need to carry the iterator, so can use an _ instead
studentname,studentemail,dayofbirth,monthofbirth,yearofbirth = input("Enter the student name, the student's email and the date of birth in the form 'name,email,day of birth,month of birth,year of birth' : ").split(",")
if studentname == "stop":
break
else:
dict1[studentname] = {'email':studentemail, 'dOB':dayofbirth, 'mOB':monthofbirth, 'yOB':yearofbirth}
while True:
name = input("From which student's email you want: ")
if name in dict1:
print(dict1[name]['email'])
else:
print(name + " not found in dict")
I am trying to solve the same a problem that does the following...
Create a program that stores Employee objects in a dictionary. Use the employee ID number as the key. The program should present a menu that lets the user perform the following actions:
Look up an employee in the dictionary
Add a new employee to the dictionary
Change an existing employee’s name, department, and job title in the
dictionary
Delete an employee from the dictionary
Quit the program
When the program ends, it should pickle the dictionary and save it to a file. Each time the program starts, it should try to load the pickled dictionary from the file. If the file does not exist, the program should start with an empty dictionary.
I found another user that posted the question here but I am having some different problems.
How should I quit the program? I tried break but it failed
miserably.
I know my formatting is atrocious but I can't figure out where it is
going wrong.
Here is what I have so far:
def main():
if os.path.exists("employee.dat"):
file = open("employee.dat","rb")
employee_dictionary = pickle.load(file)
file.close()
else:
emp1 = Employee("Susan Myers", 47899, "Accounting", "Vice President")
emp2 = Employee("Mark Jones", 39119, "IT", "Programmer")
emp3 = Employee("Joy Rogers", 81774, "Manufacturing", "Engineer")
employee_dictionary = {emp1.get_ID_number(): emp1.get_name()+ '' + emp1.get_dept()+ '' + emp1.get_job_title(),\
emp2.get_ID_number(): emp2.get_name()+ '' + emp2.get_dept()+ '' + emp2.get_job_title(),\
emp3.get_ID_number(): emp3.get_name()+ '' + emp3.get_dept()+ '' + emp3.get_job_title()}
#should I add another function here to call the employee_dictionary?
choice = 'y'
while choice.upper()== 'Y':
print("Make a selection from the following actions:")
print("Lookup an employee in the dictionary: 1")
print("Add a new employee to the dictionary: 2")
print("Change an existing employee's name, department, and job title in the dictionary: 3")
print("Delete an employee from the dictionary: 4")
print("Quit the program: 5")
selection = input("Make your selection: ")
if int(selection) == 1:
id_number = input("What is the employee's ID number?")
if int(id_number) in employee_dictionary.keys():
print(employee_dictionary[int(id_number)])
else:
print("The employee does not exist.")
else:
if int(selection) == 2:
id_number = input("What is the employee's ID number?")
if int(id_number) in employee_dictionary.keys():
print('That employee already exists.')
else:
name = input("Enter the name of the employee:")
dept = input("Enter the department of the employee:")
title = input("Enter the job title of the employee:")
emp4 = Employee(name,int(id_number), dept, title)
employee_dictionary[emp4.get_ID_number()]= emp1.get_name()+ '' + emp4.get_dept()+ '' + emp4.get_job_title()
print("The employee was added.")
else:
if int(selection) == 3:
id_number = input("What is the employee's ID number?")
if int(id_number) in employee_dictionary.keys():
name = input("Enter the name of the employee:")
dept = input("Enter the department of the employee:")
title = input("Enter the job title of the employee:")
emp4 = Employee(name,int(id_number), dept, title)
employee_dictionary[emp4.get_ID_number()]= emp1.get_name()+ '' + emp4.get_dept()+ '' + emp4.get_job_title()
print("The employee record has been updated.")
else:
print("Record not found.")
else:
if int(selection) == 4:
id_number = input("What is the employee's ID number?")
print("Deleted: ", employee_dictionary.pop(int(id_number),"Record not found."))
else:
if int(selection)!=5:
print("")
#break
choice = input("Do you want to make another selection (y or n)?")
file = open('employee.dat','wb')
pickle.dump(employee_dictionary,file)
file.close()
main()
If I create a dictionary that I need to access in multiple functions what would be the best way to pass it?
What I currently am doing keeps reseting the dictionary to empty. If I print in the addDictionary() I get the result I want. However, when I go to look up a element using the key in lookUpEntry(), I can't find it. When I print I get an empty dictionary. I also have to eventually pickle and unpickle so if anyone has any feedback on that, that would also help.
import pickle
def dictionary():
addressBook = {}
return addressBook
def addPerson():
personLastName = input("Enter the last name of "
"the person you want to add: ").lower()
personFirstName = input("Please enter the first name of "
"the person you want to add: ")
localPart = input("Please enter the local part of the email address")
while not localPart.isalnum():
localPart = input("Please enter a valid input, a-z and numbers 0-9: ")
domain = input("Please enter the domain of the email addres: ")
while not domain.isalnum():
domain = input("Please enter a valid input, a-z and numbers 0-9: ")
topLevelDomain = input("Please enter the top level domain, examples: com, net, org: ")
while not topLevelDomain.isalnum() or len(topLevelDomain) > 3:
topLevelDomain = input("Please enter only letters, a-z and not more then 3 characters: ")
personEmail = localPart + "#" + domain + "." + topLevelDomain
personStreetAddress = input("Please enter house number and street of the person you want to add: ")
personCityState = input("Please enter the city, state abbreviation and zipcode of the person you want to add: ")
personPhone = input("Please enter the phone number of the person you want to add: ")
personPhoneStr = personPhone.strip("-")
while not personPhoneStr.isdigit() and not len(personPhoneStr) == 10:
personPhone = input("Error. That is not a valid phone number. Try again: ")
personPhoneStr = personPhone.strip("-")
return personLastName, personFirstName, personEmail, personStreetAddress, personCityState, personPhone
def addDictionary():
addressBook = dictionary()
personLastName, personFirstName, personEmail, personStreetAddress, personCityState, personPhone = addPerson()
addressBook[personLastName] = personFirstName, personEmail, personStreetAddress, personCityState, personPhone
print(personFirstName,personLastName, "has been added to the address book!")
print(addressBook)
return addressBook
def lookUpEntry():
addressBook = dictionary()
keyName = input("Enter the last name of the person you are trying to find.")
while not keyName in addressBook:
keyName = input("That name is not in the address book. Please try again.").lower()
x = input("Enter '1' if you want to look up a email. Enter '2' if you want to look "
"up a persons address. Enter '3' to look up a persons phone number: ")
if x == "1":
print("The email of", addressBook[keyName[0]], keyName, "is:", addressBook[keyName[1]])
elif x == "2":
print("The address of", addressBook[keyName[0]], keyName, "is:", addressBook[keyName[2]], addressBook[keyName[3]])
elif x == "3":
print("The phone number of", addressBook[keyName[0]], keyName, "is:", addressBook[keyName[4]])
else:
print("Sorry that item is not stored in this address book.")
def main():
addDictionary()
lookUpEntry()
main()
Currently you define dictionary as
def dictionary():
addressBook = {}
return addressBook
Here you create a new dictionary every time it is called. Try replacing this with
# a global dictionary
_addressBook = {}
def dictionary():
return _addressBook