I am trying to limit the grab command to only allow 4 items to be in the list at a time as well as for the drop and edit command. I'm trying to add a message that would say invalid if the user enters any number of items that is an invalid number.
def grab(item_list):
item = input("Name: ")
item_list.append(item)
print(item + " was added.\n")
def edit(item_list):
pos = int(input("Number: "))
new_value = input("Updated name: ")
item_list[pos-1] = new_value
print("%s was updated" % (new_value))
def drop(item_list):
number = int(input("Number: "))
item = item_list.pop(number-1)
print(item + " was dropped.\n")
print()
def main():
item_list = ["wooden staff","wizard hat","cloth shoes"]
def grab(item_list):
if len(item_list)==4:
print('Cannot grab more than 4. Drop another item and try again')
return
item = input("Name: ")
item_list.append(item)
print(item + " was added.\n")
def edit(item_list):
pos = int(input("Number: "))
if not (pos-1)in range(len(item_list)):
print(str(pos) + ' not in list, try again')
edit(item_list)
return
new_value = input("Updated name: ")
item_list[pos-1] = new_value
print("Updated item %d with new value %s" % (pos, new_value))
def drop(item_list):
number = int(input("Number: "))
if not (number-1) in range(len(item_list)):
print(str(number) + ' not in list, try again')
drop(item_list)
return
item = item_list.pop(number-1)
print(item + " was dropped.\n")
print()
Related
I have a problem adding scores to an object with a for loop.
what I'm trying to achieve is this:
enter test num: 1
enter test score: 58
enter test num: 2
etc...
and then print out the three test numbers and the average, but I can't seem to get it to set the test num nor the score.
this is the error I get after tring to add test 1 and test 1 score:
Traceback (most recent call last):
File "d:\pyproj\Lecture 5\Main.py", line 27, in <module>
studentArray()
File "d:\pyproj\Lecture 5\Main.py", line 25, in studentArray s = student.setTestScore(test,score)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: student.setTestScore() missing 1 required positional argument: 'result'
Main.py
from student import student
def studentArray():
classSize = int(input("how big is the class? "))
classList = []
num=0
while not(num == classSize):
firstName = input("\nWhat's the students first name? ");
lastName = input("\nWhat's the students last name? ");
homeAddress = input("\nWhat's the students home address? ");
schoolAddress = input("\nWhat's the students school address? ");
courseName = input("\nWhat course is the students taking? ");
courseCode = input("\nWhat's the course code? ");
classList.append(student(firstName,lastName,homeAddress,schoolAddress,courseName,courseCode));
num+=1
for s in classList:
for i in range(len(classList)):
test = int(input("enter test number: "))
score = int(input("enter test score: "))
s.setTestScore(test,score)
print("\n",s)
studentArray()
studentclass.py:
from Course import Course
class student:
def __init__(self,first, last, home, school,courseName,courseCode):
self.firstName = first
self.lastName = last
self.homeAddress = home
self.schoolAddress = school
self.courseName = courseName
self.courseCode = courseCode
Course(courseName,courseCode)
self.testResults = []
def setTestScore(self,test,result):
if test < 1 | result < 0 | test > 100:
print("Error: Wrong test results.")
else:
self.testResults.append(result)
def average(self):
average = 0;
total = 0;
for result in self.testResults:
total += result
average = total / 3.0;
return average;
def __str__(self):
testAString = ""
for testResult in self.testResults:
testAString += str(testResult) + " "
result = "Student name:\n"+self.firstName + " " + self.lastName+"\n";
result += "Course name:\n"+self.courseName+"\n";
result += "Course Code: "+ self.courseCode+"\n";
result += "Test results:\n"+testAString+"\n";
result += "Average:\n", str(self.average()), "\n";
result += "Home Address:\n"+self.homeAddress+"\n";
result += "School Address:\n"+ self.schoolAddress;
return result;
Courseclass.py:
class Course:
def __init__(self,course,code):
self.course = course
self.code = code
def setCourseName(self,name):
self.course = name
def setCourseCode(self, code):
self.course = code
Issue is you are trying to run setTestScore function without instantiating the class. Either make it a staticmethod or call it from an object
for s in classList:
for i in range(len(classList)):
test = int(input("enter test number: "))
score = int(input("enter test score: "))
s.setTestScore(test,score)
print("\n"+s)
PS: Line
classList = [classSize]
creates a new list and adds classSize to the list as the first element. I assume you want to create a list with size of classSize. You do not need to specify length when creating lists in python.
Also,
testResults = []
this initalization is outside of init, which makes testResults a class variable, means it will be shared within all classes. I would advise you to move it inside init function
Editing upon your edit, you are trying to concat string with a tuple
result += "Average:\n", str(self.average()), "\n";
What you should do is:
result += "Average:\n" + str(self.average()) + "\n";
In python you don't need to end lines with ;
also you need to create an instance of the class and on that instance you can use the class methods
look in the code I added comments on every change
Main.py
from student import student
def studentArray():
classSize = int(input("how big is the class? "))
classList = []
num = 0
while num != classSize:
firstName = input("\nWhat's the students first name? ")
lastName = input("\nWhat's the students last name? ")
homeAddress = input("\nWhat's the students home address? ")
schoolAddress = input("\nWhat's the students school address? ")
courseName = input("\nWhat course is the students taking? ")
courseCode = input("\nWhat's the course code? ")
new_student = student(firstName, lastName, homeAddress, schoolAddress, courseName, courseCode)
classList.append(new_student)
number_of_test = int(input("\nHow many tests did the student had? "))
for i in range(number_of_test):
test = int(input("enter test number: "))
score = int(input("enter test score: "))
new_student.setTestScore(test, score)
num += 1
for s in classList:
print("\n" + str(s))
studentArray()
studentclass.py
from Course import Course
class student:
def __init__(self, first, last, home, school, courseName, courseCode):
self.firstName = first
self.lastName = last
self.homeAddress = home
self.schoolAddress = school
self.courseName = courseName
self.courseCode = courseCode
self.testResults = []
Course(courseName, courseCode)
def setTestScore(self, test, result):
if test < 0 or result < 0 or result > 100:
print("Error: Wrong test results.")
else:
self.testResults.append(result) # append to the list
def average(self):
average = 0
total = 0
for result in self.testResults:
total += result
average = total / 3.0
return str(average) # str the average
def __str__(self):
testAString = ""
for testResult in self.testResults:
testAString += str(testResult) + " " # str the testResult
result = "Student name:\n" + self.firstName + " " + self.lastName + "\n"
result += "Course name:\n" + self.courseName + "\n"
result += "Course Code: " + self.courseCode + "\n"
result += "Test results:\n" + testAString + "\n"
result += "Average:\n" + self.average() + "\n"
result += "Home Address:\n" + self.homeAddress + "\n"
result += "School Address:\n" + self.schoolAddress
return result
There are several issues with your code, most of them involve try to concatenate strings and non string types, as well as a few type errors along the way. You are also using the bitwise | instead of or which are not the same thing.
Starting with your student class:
use the actual or keyword instead of using bitwise |, it may be providing accurate results for some answers but it is not operating in the way you think it is.
in your __str__ method there are a few instances where you are trying to contatenate a string and an int.
in your setTestScores function you want to append the result to the testResults list.
Here is an example fix for those problems:
class student:
testResults = []
def __init__(self,first, last, home, school,courseName,courseCode):
self.firstName = first
self.lastName = last
self.homeAddress = home
self.schoolAddress = school
self.courseName = courseName
self.courseCode = courseCode
Course(courseName,courseCode)
def setTestScore(self,test,result):
if test < 1 or result < 0 or test > 100:
print("Error: Wrong test results.")
else:
self.testResults.append(result)
def average(self):
average = 0
total = 0
for result in self.testResults:
total += result
average = total / 3.0
return average
def __str__(self):
testAString = ""
for testResult in self.testResults:
testAString += str(testResult) + " "
result = "Student name:\n"+self.firstName + " " + self.lastName+"\n"
result += "Course name:\n"+self.courseName+"\n"
result += "Course Code: "+ self.courseCode+"\n"
result += "Test results:\n"+testAString+"\n"
result += "Average:\n" + str(self.average()) +"\n"
result += "Home Address:\n"+self.homeAddress+"\n"
result += "School Address:\n"+ self.schoolAddress
return result
Next you have the studentArray function.
you don't need to specify the size of the classList since lists can be dynamically appended to.
you need to convert your instance to a string before concatenating it with the new line character.
Here is an example fix for that.
def studentArray():
classSize = int(input("how big is the class? "))
classList = []
num=0
while not(num == classSize):
firstName = input("\nWhat's the students first name? ")
lastName = input("\nWhat's the students last name? ")
homeAddress = input("\nWhat's the students home address? ")
schoolAddress = input("\nWhat's the students school address? ")
courseName = input("\nWhat course is the students taking? ")
courseCode = input("\nWhat's the course code? ")
s = student(firstName,lastName,homeAddress,schoolAddress,courseName,courseCode)
classList.append(s)
num+=1
for s in classList:
for i in range(len(classList)):
test = int(input("enter test number: "))
score = int(input("enter test score: "))
s.setTestScore(test,score)
print("\n"+str(s))
Making these adjustments this was the output of your code.
how big is the class? 1
What's the students first name? a
What's the students last name? b
What's the students home address? 10
What's the students school address? 12
What course is the students taking? art
What's the course code? 1
enter test number: 1
enter test score: 88
Student name:
a b
Course name:
art
Course Code: 1
Test results:
88
Average:
29.333333333333332
Home Address:
10
School Address:
12
finally if you want to add more test scores you need add another question that asks how many tests were taken in the class and then iterate based on the response.
num_tests = int(input('how many tests'))
for s in classList:
for i in range(num_tests):
test = int(input("enter test number: "))
score = int(input("enter test score: "))
s.setTestScore(test,score)
To give you some background info, I basically have to create 2 classes called ItemToPurchase that contains an item's name, quantity, description, and price. The other class ShoppingCart adds the item's name into a list with some other functions that modify the list. The part where I am facing some issues is at the part of execute_menu(). Let's say I enter the option 'a', after I give all the details of the item, the entire program ends. I do not want that. I want the program to ask me for the next option and keep asking me the next option after I complete a specific letter's required details.
class ItemToPurchase:
def __init__(self):
self.name = 'none'
self.quantity = 0
self.price = 0
self.description = 'none'
def item_name(self, name):
self.name = name
def item_price(self, price):
self.price = price
def item_quantity(self, quantity):
self.quantity = quantity
def item_description(self, description):
self.description = description
def print_item_cost(self):
print(self.name + " " + str(self.quantity) + " # $" + str(self.price) + " = $" + str(int(self.quantity) * int(self.price)))
def print_item_description(self):
print(self.name + ": " + self.description)
class ShoppingCart:
def __init__(self, name='none', date='January 1, 2016'):
self.customer_name = name
self.current_date = date
self.cart_items = []
def add_item(self, New_cart):
self.cart_items.append(New_cart)
def remove_item(self, item_name):
count = 0
items = self.cart_items[:]
for i in range(len(items)):
item = items[i]
if item.name == item_name:
del self.cart_items[i]
count += 1
if count == 0:
print()
print('Item not found in cart. Nothing removed')
def modify_item(self, ItemToPurchase, Item_Name):
num = 0
items = self.cart_items[:]
for i in range(len(items)):
item = items[i]
if Item_Name in [x.name for x in items]:
num += 1
if ItemToPurchase.description != "none":
item.item_description(ItemToPurchase.description)
if ItemToPurchase.price != 0:
item.item_price(ItemToPurchase.price)
if ItemToPurchase.quantity != 0:
item.item_quantity(ItemToPurchase.quantity)
if num == 0:
print()
print('Item not found in cart. Nothing modified.')
print()
def get_num_items_in_cart(self):
total_number = 0
items = self.cart_items[:]
for i in range(len(items)):
item = items[i]
total_number += item.quantity
return total_number
def get_cost_of_cart(self):
total_cost = 0
items = self.cart_items[:]
for i in range(len(items)):
item = items[i]
total_cost += int(item.quantity*item.price)
return total_cost
def print_total(self):
print(self.customer_name + "'s Shopping Cart - " + str(self.current_date))
count = len(self.cart_items) + 1
if len(self.cart_items) > 0:
print('Number of items:' + str(count))
print()
for i in self.cart_items:
i.print_item_cost()
total = self.get_cost_of_cart()
print()
print('Total:', str(total))
else:
print('SHOPPING CART IS EMPTY')
def print_descriptions(self):
if len(self.cart_items) > 0:
print(self.customer_name + "'s Shopping Cart - " + str(self.current_date))
print()
print('Item Descriptions')
for j in self.cart_items:
j.print_item_description()
else:
print('SHOPPING CART IS EMPTY')
def print_menu(cart):
print('MENU')
print('a - Add item to cart')
print('r - Remove item from cart')
print('c - Change item quantity')
print("i - Output items' descriptions")
print('o - Output shopping cart')
print('q - Quit')
**def execute_menu(option, Cart):
while option != 'q':
if option == 'o':
print('OUTPUT SHOPPING CART')
Cart.print_total()
break
elif option == 'i':
print("OUTPUT ITEMS' DESCRIPTIONS")
Cart.print_descriptions()
break
elif option == 'a':
print('ADD ITEM TO CART')
print('Enter the item name:')
itemName = input()
print('Enter the item description:')
itemDescrip = input()
print('Enter the item price:')
itemPrice = int(input())
print('Enter the item quantity:')
itemQuan = int(input())
New_cart = ItemToPurchase()
New_cart.name = itemName
New_cart.quantity = itemQuan
New_cart.price = itemPrice
New_cart.description = itemDescrip
Cart.add_item(New_cart)
break
elif option == 'r':
print('REMOVE ITEM FROM CART')
print('Enter name of item to remove:')
ItemName = input()
Cart.remove_item(ItemName)
break
elif option == 'c':
print('CHANGE ITEM QUANTITY:')
print('Enter the item name:')
Item_Name = input()
print('Enter the new quantity:')
Item_Quantity = int(input())
item_s = ItemToPurchase()
item_s.item_quantity(Item_Quantity)
Cart.modify_item(item_s, Item_Name)
break**
if __name__ == "__main__":
print("Enter customer's name:")
customer = input()
print("Enter today's date:")
date = input()
print()
print('Customer name:', customer)
print("Today's date:", date)
Cart = ShoppingCart(customer, date)
option = ''
print()
print_menu(Cart)
print()
print('Choose an option:')
option = input().lower().strip()
execute_menu(option, Cart)
The reason why I am adding the break is cause the program keeps printing the end print item infinit amount of times if I do not add the break.
Any help is appreciated. thank you and have a great day ahead!
I cannot create an object of class Animal. If I do so it gives me an error saying "Unresolved reference Animal" when the #FILE I/0 code is commented out.
And if the it isn't then it gives me the error as shown in the image. Traceback most recent call: last error
Can someone help me out with this? I'm making this complete file so that I can cover the basic syntax of PYTHON.
import random
import sys
import os
import math
#SIMPLE THINGS AND MATHS
print("STARTING SIMPLE THINGS AND MATHS!!!")
print("Hello World") #This is a code for printing hello world
#Comment
"""
This
is a
multiline
comment
"""
name = "Derek"
y="2"
print (y)
print(name)
#Numbers Strings List Tuples Dictionaries
#+ - * / % ** //
name=15
print(name)
print("5 + 2 =",5+2)
print("5 - 2 =",5-2)
print("5 * 2 =",5*2)
print("5 / 2 =",5/2)
print("5 % 2 =",5%2)
print("5 ** 2 =",5**2)
print("5 // 2 =",5//2)
print("1 + 2 - 3 * 2 =", 1 + 2 - 3 * 2)
print("(1 + 2 - 3) * 2 =", (1 + 2 - 3) * 2)
quote = "\"Always remember you are unique\""
print("Single line quote: ",quote)
multi_line_quote = "\"""""Just
like everyone else""""\""
print("Multi Line quote: ",multi_line_quote)
print("%s %s %s" %('I like the quote', quote, multi_line_quote))
print("I dont like ",end="")
print("newlines")
print('\n'*5)
print("LISTS!!!")
#LISTS
grocery_list = ['Juice','Tomatoes','Potatoes',
'Bananas']
print('First item: ',grocery_list[0])
grocery_list[0] = "Green Juice"
print('First item: ',grocery_list[0])
print(grocery_list[1:3])
other_events=['Wash Car', 'Pick Up Kids','Cash Check']
to_do_list = [other_events, grocery_list] #list within a list
print(to_do_list[1][1]) #2nd item of second list
grocery_list.append('Onions')
print(to_do_list)
grocery_list.insert(1,"Pickle") #Inserting item on second index
print(to_do_list)
grocery_list.remove("Pickle") #Removing pickle from grocery list
print(to_do_list)
grocery_list.sort() #Sorting grocery list alphabetically
print(to_do_list)
grocery_list.reverse() #Sorting grocery list in reverse order albhabetically
print(to_do_list)
del grocery_list[4] #Delete item from grocery list which is on index 4
print(to_do_list)
to_do_list2 = other_events + grocery_list
print(len(to_do_list2))
print(max(to_do_list2)) #Whatever comes last alphabetically
print(min(to_do_list2)) #Whatever comes first alphabetically
to_do_list2.insert(1,"Bananas")
print(min(to_do_list2))
print("\n"*5)
#Tuples
print("TUPLES!!!")
pi_tuple=(3,1,4,1,5,9)
new_tuple=list(pi_tuple) #Converting tuple to list
new_list=tuple(new_tuple) #Converting list to tuple
print(len(new_list))
print(max(new_list))
print(min(new_list))
print("\n"*5)
#Dictionaries
print("DICTIONARIES!!!")
super_villains={'Fiddler':'Isaac Bowin',
'Captain Cold': 'Leonard Snart',
'Weather Wizard': 'Mark Mardon',
'Mirror Master': 'Sam Scudder',
'Pied Piper':'Thomas Peterson'}
print(super_villains['Captain Cold'])
print(len(super_villains))
del super_villains['Fiddler']
super_villains['Pied Piper']='Hartley Rathway'
print(len(super_villains))
print(super_villains.get("Pied Piper"))
print(super_villains.keys())
print(super_villains.values())
print("\n"*5)
#IF ElSE ELIF == != > >= < <=
print("IF ElSE ELIF (== != > >= < <=)")
age=21
if age>16:
print("You are old enough to drive")
else:
print("You are not old enough to drive")
if age>=21:
print("You are old enough to drive a tractor trailer")
elif age>=16:
print("You are old enoguh to drive a car")
else:
print("You are not old enough to drive")
#LOGICAL OPERATORS (AND OR NOT)
age=30
if ((age>=1) and (age<=18)):
print("You get a birthday")
elif (age==21)or(age>=65):
print("You get a birthday")
elif not(age==30):
print("You don't get a birthday")
else:
print("You get a birthday party yeah")
print("\n"*5)
#LOOPS
print("LOOPS!!!")
print('\n')
print("FOR LOOPS!!!")
for x in range(0,10):
print(x,' ',end="")
print('\n')
grocery_list=['Juice','Tomatoes','Potatoes','Bananas']
for y in grocery_list:
print(y)
for x in [2,4,6,8,10]:
print(x)
print('\n')
num_list=[[1,2,3],[10,20,30],[100,200,300]]
for x in range(0,3):
for y in range(0,3):
print(num_list[x][y])
print('\n'*2)
print("WHILE LOOPS!!!")
random_num= random.randrange(0,16) #Generates a random number between 0 to 99
while(random_num!=15):
print(random_num)
random_num=random.randrange(0,16)
print('\n')
i=0;
while(i<=20):
if(i==0):
i += 1
continue
elif(i%2==0):
print(i)
elif(i==9):
break
else:
i+=1 #i=i+1
continue
i+=1
print('\n')
print('Finding prime numbers')
#FINDING PRIME NUMBERS BETWEEN 0 AND 20
max_num = 20
primes = [2] # start with 2
test_num = 3 # which means testing starts with 3
while test_num < max_num:
i = 0
# It's only necessary to check with the primes smaller than the square
# root of the test_num
while primes[i] <= math.sqrt(test_num):
# using modulo to figure out if test_num is prime or not
if (test_num % primes[i]) == 0:
test_num += 1
break
else:
i += 1
else:
primes.append(test_num)
test_num += 1
print(primes)
print('\n'*5)
#FUNCTIONS
print("FUNCTIONS")
def sum(fNum,lNum):
sumNum = fNum+lNum
return sumNum
sum_of_two = sum(1,2)
print(sum_of_two)
print("The sum of 1 and 2 is: ",sum(1,2))
print('\n'*5)
#TAKE INPUT FROM USER
print("TAKE INPUT FROM USER!!!")
print("What is your name: ")
#name = sys.stdin.readline()
#print("Hello ",name)
print('\n'*5)
#STRINGS
print("STRINGS!!!")
long_string="i'll catch you if you fall - The Floor"
print(long_string[0:4])
print(long_string[-5:])
print(long_string[:-5])
print(long_string[:4] + " be there")
print("%c is my %s letter and my number %d number is %.5f" %
('X','favorite',1,.14))
print(long_string.capitalize()) #Capitalizes first letter of the string
print(long_string.find("Floor"))
print(long_string.isalpha())
print(long_string.isalnum())
print(len(long_string))
print(long_string.replace("Floor","Ground"))
print(long_string.strip()) #Strip white space
quote_list = long_string.split(" ")
print(quote_list)
print('\n'*5)
#FILE I/0
print("FILE I/0!!!")
test_file = open("test.txt","wb") #Opens the files in write mode
print(test_file.mode)
print(test_file.name)
test_file.write(bytes("Write me to the file\n", 'UTF-8')) #Writes to the file
test_file.close()
test_file = open("test.txt","r+")
text_in_file = test_file.read()
print(text_in_file)
os.remove("test.txt") #Deletes the file
print('\n'*5)
#OBJECTS
print("OBJECTS!!!")
class Animal:
__name = None #or __name = ""
__height = 0
__weight = 0
__sound = 0
def __init__(self,name,height,weight,sound):
self.__name = name
self.__height = height
self.__weight = weight
self.__sound = sound
def set_name(self, name):
self.__name = name
def set_height(self, height):
self.__height = height
def set_weight(self, weight):
self.__weight = weight
def set_sound(self, sound):
self.__sound = sound
def get_name(self):
return self.__name
def get_height(self):
return str(self.__height)
def get_weight(self):
return str(self.__weight)
def get_sound(self):
return self.__sound
def get_type(self):
print("Animal")
def toString(self):
return "{} is {} cm tall and {} kilograms and say {}".format(self.__name,
self.__height,
self.__weight,
self.__sound)
cat = Animal('Whiskers',33,10,'Meow')
print(cat.toString())
It is an indentation problem. You are creating the instance of the Aninal class with in the class. Unindent last two lines out side of class.
I'm trying to write an object-oriented program that allows me to enter and store monthly income and bills, and view all data as needed. I can successfully store an object, but when I try to use my view_all function, I get this error:
in view_all print(item.get_month())
AttributeError: 'str' object has no attribute 'get_month'
If you could help me track down this problem I'd be grateful!
# Create a month class
class Month:
# Use __init__ method to initialize the attributes
def __init__(self, month, income, tds, pnm, zia, water):
self.__month = month
self.__income = income
self.__tds = tds
self.__pnm = pnm
self.__zia = zia
self.__water = water
# The set methods accept arguments:
def set_month(self, month):
self.__month = month
def set_income(self, income):
self.__income = income
def set_tds(self, tds):
self.__tds = tds
def set_pnm(self, pnm):
self.__pnm = pnm
def set_zia(self, zia):
self.__zia = zia
def set_water(self, water):
self.__water = water
# The get methods return the data:
def get_month(self):
return self.__month
def get_income(self):
return self.__income
def get_tds(self):
return self.__tds
def get_pnm(self):
return self.__pnm
def get_zia(self):
return self.__zia
def get_water(self):
return self.__water
# The __str__ method return's the object's state as a string
def __str__(self):
return "Month: " + self.__month + \
"\nIncome: " + self.__income + \
"\nTDS: " + self.__tds + \
"\nPNM: " + self.__PNM + \
"\nZia: " + self.__zia + \
"\nWater: " + self.__water
And the main program:
import Month_Class
import pickle
ADD_MONTH = 1
VIEW_ALL = 2
QUIT = 3
FILENAME = 'ruidoso.dat'
def main():
months = load_months()
choice = 0
while choice != QUIT:
choice = get_menu_choice()
if choice == ADD_MONTH:
add_month(months)
elif choice == VIEW_ALL:
view_all(months)
save_months(months)
def load_months():
try:
input_file = open(FILENAME, 'rb')
months_dct = pickle.load(input_file)
input_file.close
except IOError:
month_dct = {}
return month_dct
def get_menu_choice():
print()
print('Menu')
print('------------------')
print("1. Add data for a new month")
print("2. View data for all months")
print('Any other number saves and quits the program!')
print()
choice = int(input('Enter your choice: '))
while choice < ADD_MONTH or choice > QUIT:
choice = int(input('Enter a valid choice: '))
return choice
def add_month(months):
month = input('Enter the name of the month: ')
income = input('Total income for this month: ')
tds = input('TDS Broadband bill total: ')
pnm = input('PNM bill total: ')
zia = input('Zia Natural Gas bill total: ')
water = input('City of Ruidoso bill total: ')
entry = Month_Class.Month(month, income, tds, pnm, zia, water)
if month not in months:
months[month] = entry
print('The entry has been added')
else:
print('That month already exists!')
def save_months(months):
output_file = open(FILENAME, 'wb')
pickle.dump(months, output_file)
output_file.close()
def view_all(months):
for item in months:
print(item.get_month())
print(item.get_income())
print(item.get_tds())
print(item.get_pnm())
print(item.get_zia())
print(item.get_water())
main()
You need to iterate over the dictionary differently
for month, item in months.items():
print(item.get_month())
...
In the view_all method, you must to iterate over dictionary:
for key, item in months.iteritems():
print(item.get_month())
and you got other error in __str__ method of Month class:
"\nPNM: " + self.__PNM + \
the correct is:
"\nPNM: " + self.__pnm + \
Hi having trouble trying to fix an error that occurs when I put just a '#' or rogue value in case someone doesn't want to add any data. I don't know how to fix it and I'm hoping to just end the code just like I would with data.
#Gets Data Input
def getData():
fullList = []
inputText = checkInput("Enter the students first name, last name, first mark, and second mark (# to exit): ")
while inputText != "#":
nameList = []
nameList2 = []
nameList = inputText.split()
nameList2.extend((nameList[0],nameList[1]))
nameList2.append((float(nameList[2]) + float(nameList [3]))/2)
fullList.append(nameList2)
inputText = checkInput("Enter the students first name, last name, first mark, and second mark (# to exit): ")
print("\n")
return fullList
#Calculates Group Average
def calc1(fullList):
total = 0
for x in fullList:
total = total + x[2]
groupAverage = total/(len(fullList))
return(groupAverage)
#Finds Highest Average
def calc2(fullList):
HighestAverage = 0
nameHighAverage = ""
for x in fullList:
if x[2] > HighestAverage:
HighestAverage = x[2]
nameHighAverage = x[0] + " " + x[1]
return (HighestAverage, nameHighAverage)
#Returns Marks above average
def results1(groupAverage,r1FullList):
r1FullList.sort()
print("List of students with their final mark above the group average")
print("--------------------------------------------------------------")
print("{:<20} {:<12}".format("Name","Mark"))
for x in r1FullList:
if x[2] > groupAverage:
name = x[0] + " " + x[1]
print("{:<20} {:<12.2f}".format(name,x[2]))
def calc3(x):
if x[2] >= 80:
return 'A'
elif x[2] >= 65:
return 'B'
elif x[2] >= 50:
return 'C'
elif x[2] < 50:
return 'D'
else:
return 'ERROR'
def results2(fullList):
print("List of Studens with their Final Marks and Grades")
print("-------------------------------------------------")
print("{:<20} {:<12} {:<12}".format("Name","Mark","Grade"))
for x in fullList:
grade = calc3(x)
name = x[0] + " " + x[1]
print("{:<20} {:<12.2f} {:<12}".format(name,x[2],grade))
#Checks for boundary and invalid data
def checkInput(question):
while True:
textInput = input(question)
if textInput == "#":
return textInput
splitList = textInput.split()
if len(splitList) !=4:
print("Invalid Format, Please Try Again")
continue
try:
a = float(splitList[2])
a = float(splitList[3])
if float(splitList[2]) < 0 or float(splitList[2]) > 100:
print("Invalid Format, Please Try Again")
continue
if float(splitList[3]) < 0 or float(splitList[3]) > 100:
print("Invalid Format, Please Try Again")
continue
return(textInput)
except ValueError:
print("Invalid Input, Please Try Again")
continue
#Main Program
#Input Data
fullList = getData()
#Process Data
groupAverage = calc1(fullList)
HighestAverage, nameHighAverage = calc2(fullList)
#Display Results
print("The group average was %.2f" % groupAverage)
print("The student with the highest mark was: %s %0.2f" %(nameHighAverage,HighestAverage))
results1(groupAverage,fullList)
print("\n")
results2(fullList)
Your program works OK for me, unless you enter a # as the first entry, in which case fullList is [] and has length 0. Hence, DivisionByZero at this line: groupAverage = total/(len(fullList)).
You could modify your code to check for this and exit:
import sys
fullList = getData()
if not fullList:
print('No Data!')
sys.exit()