Hi im pretty new to Python so I'm guessing im making a pretty obvious mistake here but basically what i'm trying to get my code to do here is to take in 5 products and their prices from the user, the products are working however when the user enters a price that is above 0 the message saying "Please enter a price above 0" is displayed, this is my code below, any help for a newbie is much appreciated thanks.
#Lists of products and prices
products = []
price = [] #declare lists
total = 0 #declare variable to hold total of prices
#function which is used to read in values to each list in turn
#range has been set to read in 5 values
def inputPrice():
for counter in range(0,5):
valid = False
print (counter+1, "Enter 5 Products:")
tempItems = input() #declare temp variable to hold input value
products.append(tempItems) #add this value into our list
#when reading in price if statement is added for validation
print (counter+1, "Enter their prices:")
tempCost = int(input())
if tempCost<=0: #validate input
print ("Incorrect price....")
print ("Please enter a price above 0")
else:
valid = True
price.append(tempCost)
Well the main key here is to loop if the condition didn't occur
products = []
price = [] #declare lists
def inputPrice():
for counter in range(1,6):
print ("Enter Product {} out of 5".format(counter))
tempItems = input() #declare temp variable to hold input value
while tempItems == '': #validate input
print ("Incorrect Product ...")
print ("Please enter a valid product")
tempItems = input()
#when reading in price if statement is added for validation
print ("Enter the price of Product {} out of 5".format(counter))
tempCost = int(input())
while tempCost <=0: #validate input
print ("Incorrect price....")
print ("Please enter a price above 0")
tempCost = int(input())
products.append(tempItems)
price.append(tempCost)
print('products' , products)
print('price' , price)
inputPrice()
Update Your Code add while loop to take prices from user
Lists of products and prices
products = []
price = [] #declare lists
total = 0 #declare variable to hold total of prices
#function which is used to read in values to each list in turn
#range has been set to read in 5 values
def inputPrice():
for counter in range(0,5):
valid = False
print (counter+1, "Enter 5 Products:")
tempItems = input() #declare temp variable to hold input value
products.append(tempItems) #add this value into our list
#when reading in price if statement is added for validation
while True:
print (counter+1, "Enter their prices:")
tempCost = int(input())
if tempCost<=0: #validate input
print ("Incorrect price....")
print ("Please enter a price above 0")
else:
break
else:
valid = True
price.append(tempCost)
inputPrice()
Related
so i have this project that I should make a program to add identify or delete data from an inventory.txt file
but when I ever try to print the inputs in the file I get messy text, what I'm looking for is a table-like structure printed inputs in the .txt file, I've tried to remove and readjust the place of \n and \t but still, I get stuff like this in the file
Samsung ide445 2154SS rams 120.0 14
Logetech Specture lid224 G502 230.0 8
here's my code for a closer look:
#This function is to get the parts information from the user
def input_parts():
#Taking the parts input from the user
try:
make = input("Enter the make: ")
model = input("Enter the model: ")
part_id = input("Enter part_id: ")
part_name = input("Enter part name: ")
price = float(input("Enter price:QR "))
quantity = int(input("Enter quantity: "))
except ValueError:
print("BOTH PRICE AND QUANTITY CAN NOT BE LETTERS, PLEASE RE-ENTER THE RIGHT DATA")
else:
#transferring both price and quantitiy to strings
price = str(price)
quantity = str(quantity)
list = ['\n'+make,model,part_id,part_name,price,quantity]
return list
#This function is to save the parts information to a file
def add_parts():
#Assignning this sentinal to make the loop repeat if the user didn't want to save
sentinal = True
while sentinal is True:
#Assigning the values of the inputs function to a variable
parts = input_parts()
#Validating user's unput
try:
#Asking the user if he wants to save the information to the file
save = input("Save? (Y/N) or Q to quit ")
except TypeError:
print("YOU CANNOT SAVE WRONG DATA IN THE FILE PLEASE RE-ENTER YOUR DATA")
else:
pass
#A boleen function to export the data to the file if the boleen is true
if save.lower() == 'y':
outfile = open('inventory.txt',"a")
#Validating user's input
try:
#Using a for loop to print the information in the file
for i in parts:
outfile.write(i+'\t')
except TypeError:
print("YOU CAN NOT SAVE WRONG DATA FILES!!!")
break
else:
pass
outfile.close
print("....Record saved.")
sentinal = False
#Using an elif statment to enable the user to re input his data
elif save.lower() == 'n':
sentinal = True
#Using an elif statment to quit if the user wants to
elif save.lower() == 'q':
break
#Using else statment to tell the user no input a valid choice
else:
print("PLEASE ENTER (Y/N) IF YOU WANT TO SAVE!!!!")
print("YOUR DATA HAS NOT BEEN SAVED")
print("PLEASE RE-ENTER YOUR DATA AND TRY AGAIN.")
sentinal = True
add_parts()
You can import tabulate module and use it as below example:
from tabulate import tabulate
print(tabulate([['Saeed', 26], ['You', 24]], headers=['Name', 'Age']))
Result:
Name Age
------ -----
Saeed 26
You 24
You may use this module to reach what you want.
I'm working on a project/exercise where I need to use OOP in Python to create a Grade Book. I've been learning Python and working with 3.8.3 for about 6 weeks now, so I'm still fairly new. The grade book has a basic menu where you can add an assignment, quiz, and final exam grades. I must use a class with an empty list for both the quiz and assignment grades. I did a rough draft of the code after reading a bit on OOP, and managed to get the class to function without using attributes and only one method as below:
class GradeBook:
def main_function():
quiz_scores = []
assignment_scores = []
while True:
try:
quiz_grade = float(input('Please enter a grade for the quiz, or press Enter to stop adding grades: '))
quiz_scores.append(quiz_grade)
except:
break
while True:
try:
assignment_grade = float(input('Please enter a grade for the assignment, or press Enter to stop adding grades: '))
assignment_scores.append(assignment_grade)
except:
break
print (quiz_scores)
print (assignment_scores)
print ('time for totals and averages')
quiz_total = sum(quiz_scores)
assignment_total = sum(assignment_scores)
print ('quiz total ' + str(quiz_total))
print ('assign total ' + str(assignment_total))
if len(quiz_scores) > 0:
quizScoreAverage = sum(quiz_scores)// len(quiz_scores)
else:
quizScoreAverage = 0
if len(assignment_scores) > 0:
assignmentScoreAverage = sum(assignment_scores) // len(assignment_scores)
else:
assignmentScoreAverage = 0
print ('quiz average ' + str(quizScoreAverage))
print ('assign average ' + str(assignmentScoreAverage))
GradeBook.main_function()
Here is where I am running into my issues. I need to split the code up into several methods/functions, one for quiz scores, one for assignment scores, one that will store the final exam score and do nothing more, and one for getting the current grade/average. I've been searching and searching but have hit a wall. The code works up until I attempt to append the user's input to the list in the class. Again this is just a rough draft of the code as follows:
class GradeBook:
# Need this at attribute level for all instances to acccess as there will be an instance the pulls the list to calculate overall grade
assignment_scores = []
# quiz_scores = [] ### - This is the other list that will also be used for the grade
def assignGrade(self, score):
self.score = score
self.assignment_scores.append(score)
#####################################################
'''
This will be a duplicate of the above code but will use values to store quiz grades instead
def quizGrade(self, score):
self.score = score
self.quiz_scores.append(score)
'''
#####################################################
while True:
try:
assignment_grade = float(input('Please enter a grade for the assignment, or press Enter to stop adding grades: '))
# Program works just fine up until this point. My issue is here. Trying to feed the user input into the class instance
# to update the class list that is stored as an attribute. Instead of appending it seems to throw an error,
# because it doesn't continue the try loop for input and after the break when the list is printed, no values are shown
assignment_grade = GradeBook.assignGrade(assignment_grade) # <------- THIS IS THE PROBLEM CHILD OF MY CODING
except:
break
#####################################################
''' This block will be used to get input for the quiz grade to append to quiz scores list
while True:
try:
quiz_grade = float(input('Please enter a grade for the assignment, or press Enter to stop adding grades: '))
quiz_grade = GradeBook.quizGrade(quiz_grade) #not sure if this is right?
except:
break
'''
#####################################################
I guess I'm just not getting a good grasp on the whole idea of sending information from one instance to another. Any input is greatly appreciated. My plan is once it all gets figured out I just need to plug in the code to my final draft here:
class GradeBook:
# Initializes empty list to store quiz and assignment grades
quiz_scores = []
assignment_scores = []
#####################################################
def quizScore(self, score)
# lines of code to append user input to quiz list for reference in class
#####################################################
def assignScore(self, score)
# lines of code to append user input to assignment list for reference in class
#####################################################
def finalScore(self, score)
# line of code to store the final exam grade for reference in the class
#####################################################
def currentAverage(self)
if len(self.assignment_scores) > 0:
assignmentScoreAverage = sum(self.assignment_scores) // len(self.assignment_scores)
else:
assignmentScoreAverage = 0
if len(self.quiz_scores) > 0:
quizScoreAverage = sum(self.quiz_scores) // len(self.quiz_scores)
else:
quizScoreAverage = 0
currentGrade = (0.4 * self.final_grade) + (0.3 * quizScoreAverage) + (0.3 * assignmentScoreAverage)
return currentGrade
#####################################################
print('''
Grade Book
0: Exit
1: Enter assignment grade
2: Enter quiz grade
3: Enter final exam grade
4: Display current grade
''')
while True:
try:
selection = int(input('Please enter a choice: '))
if selection == 0:
quit
elif selection == 1:
while True:
try:
assignment_grade = float(input('Please enter a grade for the assignment, or press Enter to stop adding grades: '))
GradeBook.assignScore(assignment_grade)
except:
break
elif selection == 2:
while True:
try:
quiz_grade = float(input('Please enter a grade for the assignment, or press Enter to stop adding grades: '))
GradeBook.quizScore(quiz_grade)
except:
break
elif selection == 3:
while True:
try:
final_grade = float(input('Please enter a grade for the assignment, or press Enter to stop adding grades: '))
GradeBook.finalScore(final_grade)
except:
break
elif selection == 3:
final_grade = float(input('Please enter a grade for the final exam: '))
if isdigit(final_grade)
GradeBook.finalScore(final_grade)
else:
print('Please check your input and try again.')
elif selection == 4:
print(GradeBook.currentAverage())
else:
print('Please check your input and try again.')
continue
(Please, use snake case for all your code, including methods. Camel case should only be used for classes) In python I would recommend creating a module(file) without class for your main function. You are using the assignGrade method as a class method. Actually, you never even created an instance of your class! To create an instance, you should call the class as follows:
my_grades = GradeBook()
Now, my_grades is "a variable"(an instance) that contains all the properties(attributes) you defined for your class. You can access them as follows:
my_grades.assignment_scores
Your loop will fail because you have not passed the self argument to the function you pointed as the problem. In python, all instance methods start with the self argument, but it will be the variable(instance) before the dot. So, you should call it from an instance of your class and not from the class itself. Using the one I created from the first example, you can change the line to:
my_grades.assignGrade(assignment_grade)
That should do.
Instead of creating and calling a main_function, in the module add the following:
if __name__ == '__main__':
... # Create your instances and manipulate them here
So following the guidelines that were provided to us, as well as the example inputs, I have the program working as intended. Since this was just an introduction class, we didn't get into using methods in separate files, so I did not use:
if __name__ == '__main__':
However, I would like any comments on it like readability and other coding practices. Working code below:
# Programmed by thelastesquire92
# Programming Assignment 7 - Grade Book App
# SEC290.B2.32789
'''
Program that focuses on Object Oriented Programming.
The user is presented with simple text menu, and following
input prompts they are allowed to enter grades for quizzes,
assignments, and a final exam. The program then calculates
the average grade based off of these inputs.
'''
class GradeBook:
# Initializes empty list for quiz and assignment grades, sets default final score to 0
quiz_scores = []
assignment_scores = []
final_exam_score = 0
#####################################################
# Adds grade input to list of quiz scores
def quiz_score(self, score):
self.quiz_scores.append(score)
#####################################################
# Adds grade input to list of assignment scores
def assignment_score(self, score):
self.assignment_scores.append(score)
#####################################################
# Updates value of final exam score
def final_score(self, score):
GradeBook.final_exam_score = score
#####################################################
# Calculates current grade average
def current_average(self):
if len(GradeBook.assignment_scores) > 0:
assignment_score_average = sum(GradeBook.assignment_scores)\
// len(GradeBook.assignment_scores)
else:
assignment_score_average = 0
if len(GradeBook.quiz_scores) > 0:
quiz_score_average = sum(GradeBook.quiz_scores)\
// len(GradeBook.quiz_scores)
else:
quiz_score_average = 0
current_grade = (0.4 * GradeBook.final_exam_score)\
+ (0.3 * quiz_score_average)\
+ (0.3 * assignment_score_average)
return current_grade
#####################################################
# Prints out the menu for user
menu = ('''
Grade Book
0: Exit
1: Enter assignment grade
2: Enter quiz grade
3: Enter final exam grade
4: Display current grade
''')
print(menu)
#####################################################
# Main body of program that loops until user selects option to exit
while True:
# Creates instance of GradeBook
my_grades = GradeBook()
try:
selection = int(input('\nPlease enter a choice: '))
#####################################################
# Option 0 that exits the program
if selection == 0:
break
#####################################################
# Option 1 that allows input for assignment grades
elif selection == 1:
while True:
try:
assignment_grade = float(input('\nPlease enter a grade for the assignment: '))
my_grades.assignment_score(assignment_grade)
break
except:
print('\nPlease check your input and try again.')
continue
#####################################################
# Option 2 that allows input for quiz grades
elif selection == 2:
while True:
try:
quiz_grade = float(input('\nPlease enter a grade for the quiz: '))
my_grades.quiz_score(quiz_grade)
break
except:
print('\nPlease check your input and try again.')
continue
#####################################################
# Option 3 that allows input for final exam grade
elif selection == 3:
while True:
try:
final_grade = float(input('\nPlease enter a grade for the final exam: '))
my_grades.final_score(final_grade)
break
except:
print('\nPlease check your input and try again.')
continue
#####################################################
# Option 4 that displays current grade average
elif selection == 4:
average = my_grades.current_average()
print('\nYour current grade average is: ' + str(average))
else:
print('\nPlease check your input and try again.')
continue
except:
print('\nPlease check your input and try again.')
print(menu)
continue
below is my code that I have worked on to get this bank atm assignment going. I can't seem to add and subtract into the balance of the code. I'm pretty sure I'm doing something wrong. Below is what the part of what the assignment entails. Everything else is in working order in regards to choosing option P, S, and E. Options D, and W are where I have run into a problem. Any help would be great. Thanks!
If the user types D then:
· Ask the user for the account number.
· Search the accountnumbers() array for that account number and find its position.
· Ask the user for the amount to be deposited.
· Add the deposit amount to the balance for that account.
· If the user types W then:
· Ask the user for the account number.
· Search the accountnumbers() array for that account number and find its position.
· Ask the user for the amount to be withdrawn.
· Subtract withdrawal amount from the balance for that account.
namelist=[]
accountnumberslist=[]
balancelist=[]
def populatelist():
print ('Great! Please enter the information below')
namecount=0
#This loops collects the five names,accounts,balances, and appends them to the namelist
while(namecount< 2):
name= input('Enter a name: ')
namelist.append(name)
accountnumber = input('Please enter your Account Number: ')
accountnumberslist.append(accountnumber)
balances = input('Please enter your Balance: ')
balancelist.append(balances)
namecount = namecount + 1
return
def displayall():
print ('I am inside display function')
position =0
#This loop, prints one name at a time from the zero position to the end.
while ( position < 2):
displayone(position)
position = position + 1
return
def displayone(position):
print ('Account Holder:',namelist[position])
print ('Balance:',balancelist[position])
return
def calculatedeposit():
position = 0
while (position < 2):
depamount = int(input('Please enter the amount to deposit'))
balancelist[position] = balancelist[position] + depamount
position = position + 1
return
def calculatewithdrawal()
position = 0
while (position < 2):
withmount = int(input('Please enter the amount to deposit'))
balancelist[position] = balancelist[position] + withamount
position = position + 1
#What does it receive. Account Number to search.
#what does it do? Searches for the Account Holder.
#what does it send back. Position of the Account Holder, if not found, -1
def searchforacct(accounttosearch):
foundposition=-1 # assume that it is not going to be found.
position=0
while (position < 2):
if (accounttosearch==accountnumberslist[position]):
foundposition = position
break
position = position + 1
return foundposition
#This function will display the menu, collect the users response and send back
def displaymenu():
print ('Enter P to Populate Data')
print ('Enter S to Search for Account ')
print ('Enter D to Deposit Amount ')
print ('Enter W to Withdraw Amount ')
print ('Enter E to Exit')
choice = input('How can we help you today?:')
return choice
print("=====================================")
print(" Welcome to Liberty City Bank ATM ")
print("=====================================")
#main
response=''
while response!= 'E' and response!='e':
response = displaymenu()
if response=='P' or response=='p':
populatelist()
elif response=='S' or response=='s':
accounttosearch = input('Please enter the Account Number to search:')
foundpos = searchforacct(accounttosearch)
if ( foundpos == -1 ):
print ('Account not found')
else:
displayone(foundpos)
elif response=='D' or response=='d':
accounttosearch = input('Please enter the Account Number for Deposit:')
foundpos = searchforacct(accounttosearch)
if ( foundpos == -1 ):
print ('Account not found')
else:
calculatedeposit()
elif response=='W' or response=='w':
accounttosearch = input('Please enter the Account Number for Withdrawal:')
foundpos = searchforacct(accounttosearch)
if ( foundpos == -1 ):
print ('Account not found')
else:
calculatewithdrawal()
elif response=='E' or response=='e':
print ('Thank you for choosing Liberty City Bank!')
print ('Have a Nice Day!')
else:
print ('Invalid choice. Please try again')
Your code wont compile, on line 45 add a : following your def. On line 45 change withamount to withmount. Then on Line 45 change
balancelist[position] = balancelist[position] + withamount
to this
balancelist[position] = int(balancelist[position]) - withamount
You need to cast the string in your balance list to an int. You also need to subtract (-) not add (+) from the list as its a withdrawal.
There are a few other bugs in your code but thats enough to get you up and running.
Instead of looking at the 'account' you found from the users input, you loop through the first 2 balance lists and add a user given value.
Here is what i am trying to do.. I want the user to pick a number, and then print word from my list that the number indexes.
This is what i have so far
mylist = ["john","jack","jen","judy","jill"]
mylist
add = input("please state a name")
mylist.append(add)
print (mylist)
add = input("please state a number")
This would work:
index = input("please state a number")
index = int(index)
name = mylist[index]
print(name)
Here is a little bit of code suposed to create a list of expenses with name and amount:
def make_list():
expense_list = []
for count in range(1, 5):
print "expense number" + str(count) + ":"
name = raw_input(' enter expense name: ')
amount = raw_input(' enter expense amount: ')
return expense_list
make_list()
What am I doing wrong? Even in interactive mode I can't seem to figure out how to get my item.
Your indentation is wrong, you never actually add anything to your list and you don't assign the returned list to anything. Also, the "magic number" (5) isn't ideal. Try:
def make_list(n):
expense_list = []
for count in range(1, n+1):
print "expense number {0}:".format(count)
name = raw_input(' enter expense name: ')
amount = raw_input(' enter expense amount: ')
expense_list.append((name, amount))
return expense_list
l = make_list(4)
print l