I need to somehow access the class dictionary and delete it with the removeClass() function, not sure how to pass the class in it though. This program is supposed to remove the class from the dictionary when the number 2 option is selected.
I'm not sure what to do here.
def prompt():
print('MENU')
print('1 --> Add classes.')
print('2 --> Remove classes.')
print('3 --> View course details.')
print('4 --> View schedule.')
print('5 --> Quit.')
option = int(input('What would you like to choose? '))
while option < 1 or option > 5:
option = int(input('Please enter a valid numerical option: '))
return option
def checkOption(option):
if option == 1:
courseCount = 0
courseCount = courseCounter()
classes = addClasses(courseCount)
elif option == 2:
removeClasses(courses)
elif option == 3:
viewCourseDetails()
elif option == 4:
viewSchedule()
def courseCounter():
courseCount = input('Enter a numerical value of courses only (up to 4): ')
while courseCount.isnumeric() == False:
courseCount = input('Enter a NUMERICAL value of courses only (up to 4): ')
return int(courseCount)
def addClasses(courseCount):
classes = {}
i = 1
while i <= courseCount:
courseName = input('Enter a course name: ')
classes[courseName] = {}
classes[courseName]['Room Number'] = input('Enter a room number: ')
classes[courseName]['Instructor'] = input('Enter a instructor: ')
classes[courseName]['Meeting time'] = input('Enter a meeting time: ')
i = i + 1
return classes
def removeClasses(*****):
courseName = input('Enter the class you would like to remove: ')
if ***** in classes:
del classes[courseName]
print(classes)
def main():
option = prompt()
checkOption(option)
while option > 1 or option < 5:
if option == 5:
break
option = prompt()
checkOption(option)
main()
Through globals() variables so you can pass it across functions:
def prompt():
print('MENU')
print('1 --> Add classes.')
print('2 --> Remove classes.')
print('3 --> View course details.')
print('4 --> View schedule.')
print('5 --> Quit.')
option = int(input('What would you like to choose? '))
while option < 1 or option > 5:
option = int(input('Please enter a valid numerical option: '))
return option
def checkOption(option):
if option == 1:
courseCount = 0
courseCount = courseCounter()
classes = addClasses(courseCount)
elif option == 2 :
if 'classes' in globals() :
removeClasses(globals()['classes'])
else :
print("Insert a class before!")
checkOption(1)
elif option == 3:
viewCourseDetails()
elif option == 4:
viewSchedule()
def courseCounter():
courseCount = input('Enter a numerical value of courses only (up to 4): ')
while courseCount.isnumeric() == False:
courseCount = input('Enter a NUMERICAL value of courses only (up to 4): ')
return int(courseCount)
def addClasses(courseCount):
classes = {}
i = 1
while i <= courseCount:
courseName = input('Enter a course name: ')
classes[courseName] = {}
classes[courseName]['Room Number'] = input('Enter a room number: ')
classes[courseName]['Instructor'] = input('Enter a instructor: ')
classes[courseName]['Meeting time'] = input('Enter a meeting time: ')
i = i + 1
globals()[ 'classes' ] = classes
return classes
def removeClasses(classes):
courseName = input('Enter the class you would like to remove: ')
if courseName in classes:
del classes[courseName]
print(classes)
def main():
option = prompt()
checkOption(option)
while option > 1 or option < 5:
if option == 5:
break
option = prompt()
checkOption(option)
main()
This works on my machine. This also check for existence of classes or redirect user to define classes.
Be awared of globals() behave (e.g. Why are global variables evil?). Otherwise you can define an object (an empty dictionary) and pass it through functions, filling it or check if is empty, that is probably safer.
The simplest way I can think of is as follows. I modified 2 of your functions and made 'classes' global.
classes = {}
def checkOption(option):
global classes
if option == 1:
courseCount = courseCounter()
classes = addClasses(courseCount)
elif option == 2:
removeClasses()
elif option == 3:
viewCourseDetails()
elif option == 4:
viewSchedule()
def removeClasses():
courseName = input('Enter the class you would like to remove: ')
if courseName in classes:
del classes[courseName]
print(classes)
I hope this helps you.
Related
I have been trying different code combinations for three days now and I figured before i throw in the towel this might be a good place to ask my question. In my code, no matter how I try to declare the lists I've been unsuccessful. My problem currently is:
line 54, in main
inputExpenseAmounts(expenseItems)
UnboundLocalError: local variable 'expenseItems' referenced before assignment
import matplotlib.pyplot as plt
from prettytable import PrettyTable
def menu():
print('[1] Enter Expense Name')
print('[2] Enter Expense Amount')
print('[3] Display Expense Report')
print('[4] Quit')
choice = input('Enter choice: ')
return choice
def inputExpenseNames():
expenseItems = []
name = input("Enter expense name (q for quit) \n")
while name != "q" :
expenseItems.append(name)
name = input("Enter expense name (q for quit) \n")
return expenseItems
def inputExpenseAmounts(expenseItems):
expenseAmounts = []
print("Enter the amount for each expense ")
for i in expenseItems:
amount = int(input(i + " : "))
expenseAmounts.append(amount)
return ExpenseAmounts
def displayExpenseReport(expenseItems, expenseAmounts):
displayExpenseReport = []
option = input("Display in \n (a) table \n (b) bar chart \n (c) pie chart \n")
if option == "c":
plt.pie(expenseAmounts, labels = expenseItems)
plt.show()
elif option == "b":
plt.bar(expenseItems, expenseAmounts)
plt.show()
elif option == "a":
t = PrettyTable()
t.add_column("expenseItems",expenseItems)
t.add_column("expenseAmounts",expenseAmounts)
print(t)
else:
print("Invalid option - allowed only (a / b / c")
def main():
while True:
choice = menu()
if choice == '1':
inputExpenseNames()
elif choice == '2':
inputExpenseAmounts(expenseItems)
elif choice == '3':
displayExpenseReport(expenseItems, expenseAmounts)
elif choice == '4':
break
else:
print('Invalid selection. Please re-enter.')
expenseItems = inputExpenseNames()
main()
The error is telling you that you used a variable (expenseItems) that hadn't been defined yet.
What you probably want to do is initialize those variables to empty lists, and then store the results of calling your earlier menu functions so you can pass them to the later functions.
def main():
expenseItems = []
expenseAmounts = []
while True:
choice = menu()
if choice == '1':
expenseItems = inputExpenseNames()
elif choice == '2':
expenseAmounts = inputExpenseAmounts(expenseItems)
elif choice == '3':
displayExpenseReport(expenseItems, expenseAmounts)
elif choice == '4':
break
else:
print('Invalid selection. Please re-enter.')
I'll note that you may want to rethink the idea of having a menu here, since the user always must go through the items in the exact order they're listed. It would be simpler to just automatically go through the three steps in order.
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)
I have a python function and would like to retrieve a value from outside the function. How can achieve that without to use global variable. I had an idea, if functions in python are objects then this could be a right solution?
def check_difficulty():
if (difficulty == 1):
check_difficulty.tries = 10
elif (difficulty == 2):
check_difficulty.tries = 5
elif (difficulty == 3):
check_difficulty.tries = 3
try:
difficulty = int(input("Choose your difficulty: "))
check_difficulty()
except ValueError:
difficulty = int(input("Type a valid number: "))
check_difficulty()
while check_difficulty.tries > 0:
I am new to python so excuse me...
def check_difficulty(difficulty):
if (difficulty == 1):
return 10
elif (difficulty == 2):
return 5
elif (difficulty == 3):
return 3
tries = 0
while tries > 0:
difficulty = int(input("Choose your difficulty: "))
tries = check_difficulty(difficulty)
tries = tries - 1
if you use a while loop and put everything inside in a structured way, a function will not be needed.
You can change this to a class to get your tries:
class MyClass:
def __init__(self):
self.tries = 0
def check_difficulty(self, difficulty):
if (difficulty == 1):
self.tries = 10
elif (difficulty == 2):
self.tries = 5
elif (difficulty == 3):
self.tries = 3
ch = MyClass()
try:
difficulty = int(input("Choose your difficulty: "))
ch.check_difficulty(difficulty)
except ValueError:
difficulty = int(input("Type a valid number: "))
ch.check_difficulty(difficulty)
ch.tries
# 5
If you want the question answered within the construct of your current code simply put your try, except before the function. You can call a function anywhere in the code it doesn't ave to be after the function is created . So something like this:
try:
difficulty = int(input("Choose your difficulty: "))
check_difficulty()
except ValueError:
difficulty = int(input("Type a valid number: "))
check_difficulty()
def check_difficulty():
if (difficulty == 1):
check_difficulty.tries = 10
elif (difficulty == 2):
check_difficulty.tries = 5
elif (difficulty == 3):
check_difficulty.tries = 3
while check_difficulty.tries > 0:
however, I would have to agree with the other answers and just kind of put everything together within the same loop and you won't have to worry about this. I created a guessing game recently that actually had something similar to this. Here is the difficulty portion of that code:
def guessing_game():
again = ''
# Define guesses/lives
while True:
try:
guesses_left = int(input('How many guess would you like(up to 4)?: '))
if 1 > guesses_left or guesses_left > 4:
print('You must choose between 1 and 4 for your guess amount. Try again.')
continue
break
except:
print('You must enter a valid number between 1 and 4. Try again.')
# Define difficulty based on guesses_left
difficulty = ''
if guesses_left == 1:
difficulty = 'Hard Mode'
elif guesses_left == 2:
difficulty = 'Medium Mode'
elif guesses_left == 3:
difficulty = 'Easy Mode'
elif guesses_left == 4:
difficulty = 'Super Easy Mode'
print('You are playing on ' + difficulty + ' with ' + str(guesses_left) + ' guesses.')
#code continues under this line to finish#
How would I stop my code looping after it has added the amount of names the user has inputted instead of doing this:
Add Name
Show list
Quit
Enter your choice : 1
How many names would you like to enter: 2 # How would I set a max of 10 names here?
Enter name: Bob
Enter name: Jim
How many names would you like to enter: # How would I stop this line from repeating?
Actual code:
names = []
def displayMenu():
print(" 1. Add Name")
print(" 2. Show list")
print(" 3. Quit")
choice = int(input("Enter your choice : "))
while choice >5 or choice <1:
choice = input("Invalid. Re-enter your choice: ")
return choice
def addname():
while True:
number=int(input('How many names would you like to enter: '))
name = [input('Enter name:') for _ in range(number)]
names.append(name)
def displayData():
#name.split(",") how would i correctly user split here
print(names)
option = displayMenu()
while option != 3:
if option == 1:
addname()
elif option == 2:
displayData()
option = displayMenu()
print("Program terminating")
Okay, first off, since you only have three menu options, this line:
while choice >5 or choice <1:
Should look like this:
while 3 < choice < 1:
So your displayMenu function looks like this:
names = []
def displayMenu():
print(" 1. Add Name")
print(" 2. Show list")
print(" 3. Quit")
choice = int(input("Enter your choice : "))
while 3 < choice < 1: # Only accept choices in between 3 and 1
choice = input("Invalid. Re-enter your choice: ")
return choice
You also said that your addname function was looping forever, this is because you have an infinite while loop.
What you need, as #ettanany said, is a for loop:
In your case, for loop would work also:
def addname():
number = int(input('How many names would you like to enter: '))
for i in range(number):
name = input('Enter name: ')
names.append(name)
What this does is ask the user how many names he wants to enter, and then runs the code inside the loop for that amount of times -- so if the user enters the number 9, it will ask for 9 names.
You also said that there should be a maximum of 10 names. We can use a while loop like you did in the displayMenu function to make sure the user enters a number that is 10 or below:
def addname():
number = int(input('How many names would you like to enter: '))
while number > 10: # Don't allow any numbers under 10
number = int(input('Please enter a number under 10: '))
for i in range(number):
name = input('Enter name: ')
names.append(name)
Finally, in your displayData function, you want to 'split' the names and print them out.
Just doing print(names) would give us a result like this:
[ 'Spam', 'Eggs', 'Waheed' ]
If we want it to look nice, we need to use a for loop.
for name in names:
print( name ) # You can change this line to print( name, end=' ' )
# If you want all the names on one line.
This will yield a result like this:
Spam
Eggs
Waheed
Which looks much better than just printing out the list.
Complete (fixed) code:
names = []
def displayMenu():
print(" 1. Add Name")
print(" 2. Show list")
print(" 3. Quit")
choice = int(input("Enter your choice : "))
while 3 < choice < 1: # Only accept choices in between 3 and 1
choice = input("Invalid. Re-enter your choice: ")
return choice
def addname():
number = int(input('How many names would you like to enter: '))
while number > 10: # Don't allow any numbers under 10
number = int(input('Please enter a number under 10: '))
for i in range(number):
name = input('Enter name: ')
names.append(name)
def displayData():
for name in names:
print( name ) # You can change this line to print( name, end=' ' )
# If you want all the names on one line.
option = displayMenu()
while option != 3:
if option == 1:
addname()
elif option == 2:
displayData()
option = displayMenu()
print("Program terminating")
Instead of while True, you need to use while i < number, so your addname() function should be as follows:
def addname():
i = 0
number = int(input('How many names would you like to enter: '))
while i < number:
name = input('Enter name: ') # We ask user to enter names one by one
names.append(name)
i += 1
In your case, for loop would work also:
def addname():
number = int(input('How many names would you like to enter: '))
for i in range(number):
name = input('Enter name: ')
names.append(name)
I am getting this invalid syntax for if selection == 1: under def mainmenu(): Do not understand why I am getting this error. Please help me figure this out. I completely doesnt make any sense to me why its there.
contacts = {}
class person:
def ___init__(self,first,last,number):
self.first = first
self.last = last
self.number = number
def get_info(self):
print(first,last,number)
class friend(person):
def __init__(self,email,bday):
self.email = email
self.bday = bday
def get_info_friend(self):
super().get_info()
print(email,bday)
def add_a_contact():
choice = int(input("Contact type: \n\t 2: Person \nEnter an option here:"))
first = input("Enter the first name:")
last = input("Enter the last name:")
number = input("Enther the number:")
if choice == 1:
email = input("Email Address is:")
bday = input("Their bday is:")
return Friend(email,bday,first,last,number)
return person(first,last,number)
def add_contact_to_dict():
contact = add_a_contact()
contacts[contact.last_name] = contact
def lookup():
last = input("What is their last name?:")
if last in contacts:
contact = contacts[last]
print("Name&number: ", contact.first,contact.last,contact.number)
if type(friend) is friend:
print("Email and Bday is: ", contact.email,contact.bday)
def mainmenu():
selection = 0
temp = ""
while selection != 3:
print("Select an option: \n\t 1: Add \n\t 2: Lookup \n\t 3: Exit")
selection = int(input("Enter an option:")
if selection == 1:
temp = add_contact_to_dict()
elif selection == 2:
lookup()
elif selection == 3:
pass
else:
print("Not a valid option")
if __name__ == "__mainmenu__":
mainmenu()
So when you are asked for the input under selection, you need another bracket to for the "int" part. Hopefully, that should solve your issue.