Here is a small chunk of a code I have:
studentName = ""
def getExamPoints (total):
for i in range (4):
total = 0.0
examPoints = input ("Enter exam score for " + studentName + str(i+1) + ": ")
total = ?????
total = total/.50
total = total * 100
where the ????? is I can't figure out how to get the string to add the four scores
student name I inputed later and it is required that later in the program I use examPoints = getExamPoints(studentName).
Without any error checking for bad input:
total = 0.0
for i in range (4):
total += int(input ("Enter exam score for " + studentName + str(i+1) + ": "))
total = total/.50
total = total * 100
Did you try
total += int(examPoints);
Related
im learning python and for my homework i wanna make a food ordering program and get the receipt of the products purchased with the prices for the total. im struggling to get the billing process as i cannot get all the products chosen by the user displayed on the receipt
import datetime
x = datetime.datetime.now()
name = input("Enter your name: ")
address = input("Enter your address: ")
contact = input("Enter your phone number: ")
print("Hello " + name)
print("*"*31 + "Welcome, these are the items on on the menu."+"*" * 32 )
print("Menu:\n"
"1.Burger:150.\n"
"2.Fried Momo:120.\n"
"3.coffee:60.\n"
"4.Pizza:180.\n"
"5.Fried Rice:150.\n"
"6.French Fries:90.\n"
"7.Steamed Dumplings:150.\n"
"8.Chicken drumsticks:120.\n"
"9.Chicken Pakoras:120.\n"
"10.American Chop Suey:200.\n")
prices = {"1.Burger":150,
"2.Fried Momo":120,
"3.coffee":60,
"4.Pizza":180,
"5.Fried Rice":150,
"6.French Fries":90,
"7.Steamed dumplings":150,
"8.Chicken drumsticks":120,
"9.Chicken Pakoras":120,
"10.American Chop Suey":200
}
continue_order = 1
total_cost, total = 0, 0
cart = []
while continue_order != 0:
option = int(input("Which item would you like to purchase?: "))
cart.append(option)
if option >= 10:
print('we do not serve that here')
break
elif option == 1:
quantity = int(input("Enter the quantity: "))
total = quantity * 150
print("The price is: ₹" + str(total))
elif option == 2:
quantity = int(input("Enter the quantity: "))
total = quantity * 120
print("The price is: " + str(total))
elif option == 3:
quantity = int(input("Enter the quantity: "))
total = quantity * 60
print("The price is: " + str(total))
elif option == 4:
qquantity = int(input("Enter the quantity: "))
total = quantity * 180
print("The price is: " + str(total))
elif option == 5:
quantity = int(input("Enter the quantity: "))
total = quantity * 150
print("The price is: " + str(total))
elif option == 6:
quantity = int(input("Enter the quantity: "))
total = quantity * 90
print("The price is: " + str(total))
elif option == 7:
quantity = int(input("Enter the quantity: "))
total = quantity * 150
print("The price is: " + str(total))
elif option == 8:
quantity = int(input("Enter the quantity: "))
total = quantity * 120
print("The price is: " + str(total))
elif option == 9:
quantity = int(input("Enter the quantity: "))
total = quantity * 120
print("The price is: " + str(total))
elif option == 10:
quantity = int(input("Enter the quantity: "))
total = quantity * 200
print("The price is: " + str(total))
total_cost += total
continue_order = int(input("Would you like another item? enter Yes--> (1) or--> No (0):"))
print('='*30)
print('='*30)
print("Your receipt:\n")
print("Date: " + str(x))
print("Name: " + name.title())
print("Adress: " + address)
print("Contact number: " + contact)
for option in cart:
print ("Item: %s. Price: %s") % (option, prices[option])
print("Quantity: ",quantity)
print("Total Price: ", total_cost)
print('='*30)
print("Thank you for shopping here, have a great day ")
print('='*30)
but i get an error line 95, in
print ("Item: %s. Price: %s") % (option, prices[option])
KeyError: 1
any solution or better ways to improve the code would be really great
Try using F-Strings. They let you format text far more easily. Here's an example.
x = "hello!"
print(f"shr4pnel says {x}")
>>> shr4pnel says hello!
The problem in this case is that option == 1. 1 isn't a key in the dictionary so nothing is output. Hope this helps. This is because the dictionary does not have 1 as a key. To access the item the dictionary would have to be formatted like this.
prices = {1: "burger", 2: "hot dog"}
print(prices[1])
>>> burger
Why the program does not want to calculate the average value from the dictionary?
grades = {}
def addGrade(grades):
course = input("input course: ")
grade = int(input("input grade: "))
grades[course] = grade
def printGrades(grades):
print("all grades:")
for c, grade in grades.items():
print(c + "\t" + str(grade))
def count(grades):
n = len(grades.keys())
print(n)
def printAverage(grades):
print("average grade:" + sum(grades)/int(count))
You have to add:
count = len(grades.keys())
Because it is not defined in your function.
The correct version of your function is:
def printAverage(grades):
count = len(grades.keys())
print("average grade:" , sum(grades.values())/count)
You have to use
sum(grades.values())
Otherwise it will be adding up all the keys instead of the values (grades).
The following should work:
grades = {}
def addGrade():
course = input("input course: ")
grade = int(input("input grade: "))
grades[course] = grade
def printGrades():
print("all grades:")
for c, grade in grades.items():
print(c + "\t" + str(grade))
def count():
n = len(grades.keys())
return n
def printAverage():
print(f"average grade: {sum(grades.values()) / len(grades):.2f}")
if __name__ == '__main__':
number_of_courses = int(input('Enter number of courses: '))
for _ in range(number_of_courses):
addGrade()
printAverage()
sample output:
This question already has answers here:
How can I simplify repetitive if-elif statements in my grading system function?
(14 answers)
Closed 1 year ago.
I am new to Python and I am having a hard time getting this right.
As the title says, how I can get the equivalent marks based on the percentage results.
print('<-------------------------------------------->')
print(' Grade Evaluation Program ')
print('<-------------------------------------------->')
last_name = input('Enter Last Name: ')
first_name = input('Enter First Name: ')
middle_initial = input('Enter Middle Initial: ')
section_code = input('Enter Section Code: ')
print('<-------------------------------------------->')
print(' Input Scores ')
print('<-------------------------------------------->')
try:
quiz_one = float(input('Enter Quiz 1 Score: '))
quiz_one_totalScore = float(input('Enter Quiz 1 Total Points: '))
quiz_two = float(input('Enter Quiz 2 Score: '))
quiz_two_totalScore = float(input('Enter Quiz 2 Total Points: '))
homework_one = float(input('Enter Homework 1 Score: '))
homework_one_totalScore = float(input('Enter Homework 1 Total Points: '))
homework_two = float(input('Enter Homework 2 Score: '))
homework_two_totalScore = float(input('Enter Homework 2 Total Points: '))
exam_score = float(input('Enter Exam Score: '))
exam_totalScore = float(input('Enter Exam Total Points: '))
except:
print('Please enter a whole number.')
exit()
print('<-------------------------------------------->')
print(' Results ')
print('<-------------------------------------------->')
firstResult = (((quiz_one + quiz_two) / (quiz_one_totalScore + quiz_two_totalScore)) * 100) * 0.30
secondResult = (((homework_one + homework_two) / (homework_one_totalScore + homework_two_totalScore)) * 100) * 0.20
thirdResult = ((exam_score / exam_totalScore) * 100) * 0.50
overall_grade = format(firstResult + secondResult + thirdResult, ".2f")
print('Student Name: ' + last_name + ', ' + first_name + ' ' + middle_initial + '.')
print('Section Code: ' + section_code)
print('Percentage Grade: ' + str(overall_grade) + '%')
print('Equivalent Grade: ' ) #DisplayPercentageEquivalentGradeHere
print('<-------------------------------------------->')
I tried other solutions like the if-else statement but it just confused me more. Would really appreciate if you could teach me how.
The equivalent marks for each percentage are:
94-100 = 1
88-93 = 1.25
82-87 = 1.5
76-81 = 1.75
70-75 = 2
64-69 = 2.25
58-63 = 2.5
52-57 = 2.75
50-51 = 3
30-49 = 4
0-29 = 5
Yes if-statements will do.
if overall_grade >= 94:
print (1)
elif overall_grade >= 88:
print (1.25)
elif overall_grade >= 82:
print (1.5)
...
else:
print (5)
This program will ask the user for the number of half-dollars, quarters, dimes, nickels, and pennies s/he has and then compute the total value. The total value of the change is shown both as the total number of cents and then as the separate number of dollars and cents. I want to include a final total that displays after the user is finished; which will display the total of all amounts entered throughout the session(i.e. all loop iterations). So how can I code this?
#getCoin function
def getCoin(coinType):
c = -1
while c < 0:
try:
c = int(input("How many " + coinType + " do you have? "))
if c < 0:
print("Coin counts cannot be negative. Please re-enter.")
except ValueError:
print("llegal input. Must be non-negative integer. Re-enter.")
c = -1
return c
print("Welcome to the Change Calculator")
print()
choice = input ("Do you have any change (y/n)?")
while choice.lower() == "y":
h = getCoin("Half-Dollars")
q = getCoin("Quarters")
d = getCoin("Dimes")
n = getCoin("Nickel")
p = getCoin("Pennies")
print()
TotalVal = (h*50) + (q*25) + (d*10) + (n*5) + p
print("You have " + str(TotalVal) + " cents.")
dollars = TotalVal // 100 # // is for division but only returns whole num
cents = TotalVal % 100 # % is for modulos and returns remainder of whole number
print("Which is " + str(dollars) + " dollars and " + str(cents) + " cents.")
choice = input("Do you have more change (y/n)? ")
print("Thanks for using the change calculator.")
finalTotal = TotalVal
print("You had a total of" + finalTotal + " cents.")
print("Which is" + str(finalTotalDollars) + " dollars and" + str(finalTotalCents) + " cents.")
To make it so when a user wants to play again, you could use an external file to write to and read from using open, read and write, to store user info.
You could use notepad as .txt and write user name, money, and repeat, so login checks and calls the money at the line after the name.
#Program to calculate cost of gas on a trip
#Created by Sylvia McCoy, March 31, 2015
#Created in Python
#Declare Variables
Trip_Destination = 0
Number_Miles = 0
Current_MPG = 0.0
Gallon_Cost = 0.0
Total_Gallons = 0.0
Total_Cost = 0.0
#Loop to enter destinations
while True:
Trip_Destination = input("Enter where you would like to travel: ")
Number_Miles = float(input("Enter how many miles to your destination: "))
Gallon_Cost = float(input("Enter how much a gallon of gas costs: "))
Current_MPG = float(Number_Miles / Gallon_Cost)
print("Your trip to: " + Trip_Destination)
print("Your total miles: " + Number_Miles)
print("Your MPG: " + Current_MPG)
Error in line 20 and 21...stated earlier as float, how do I get them to print? Have to do the work in Python. Thanks!
You can't use the + operator to combine a string with a float.
It can only be used to combine two of a single type (eg.2 strings, 2 floats, etc.)
With that said, to get your desired output, you can simplify ALL the conversions you need into one line, like so:
Trip_Destination = 0
Number_Miles = 0
Current_MPG = 0.0
Gallon_Cost = 0.0
Total_Gallons = 0.0
Total_Cost = 0.0
#Loop to enter destinations
while True:
Trip_Destination = input("Enter where you would like to travel: ")
Number_Miles = input("Enter how many miles to your destination: ")
Gallon_Cost = input("Enter how much a gallon of gas costs: ")
Current_MPG = str(float(Number_Miles) / float(Gallon_Cost))
print("Your trip to: " + Trip_Destination)
print("Your total miles: " + Number_Miles)
print("Your MPG: " + Current_MPG)
Using the input() function by itself will let you get a value from the user (already in the form of a string). This way, you won't have to format/convert it later.
Check this out
while True:
Trip_Destination = input("Enter where you would like to travel: ")
Number_Miles = float(input("Enter how many miles to your destination: "))
Gallon_Cost = float(input("Enter how much a gallon of gas costs: "))
Current_MPG = float(Number_Miles / Gallon_Cost)
print("Your trip to: " + Trip_Destination)
print("Your total miles:{}".format(Number_Miles))
print("Your MPG:{}".format(Current_MPG))
print("your string {}".format(x))
its called string formatting
Concatenation
You are trying to add a string and a float, in Python the two won't be automatically casted.
print("Your total miles: " + str(Number_Miles)) # same for miles per gallon
String Formats
Otherwise, you can also use string formatting in order to interpolate the desired variable.
print("Your total miles: {0}".format(Number_Miles)) # same miles per gallon