I'm trying to ask the user to input how many classes they have (x), ask "What are your grades in those classes?" x amount of times, and record all of the inputted grades to use later.
I tried to assign the question to a variable and ask to print the variable, but I get only the last inputted number. I don't want to print the numbers, I want to store them for later so I can add them together. I was just using the print function to see how my numbers would be stored if assigning the variable actually worked. How would I record all the inputted numbers to later add and calculate GPA?
numofclasses = int(input("How many honors classes do you have?: "))
for i in range(numofclasses):
grades = str(input("Enter the unweighted grade from one class "))
print(grades)
I want to get all the inputted numbers recorded, but by using the print option I only get the last inputted number recorded.
The thing you want to use is a list, which is used to container which holds a sequence of datatypes, like integer, characters, etc,
Think of it this way, if you want to use 3 variables in python what would you generally do
a = 1
b = 2
c = 3
This works fine, but what if the number of variables is 50, or 100, how many variables will you keep defining, hence you would need a container to store these, which is where a list comes in. So we would just do
li = [1,2,3]
And access these variables via indexes, which start from 0
a[0] #1
a[1] #2
a[2] #3
Keeping this in mind, we would do!
numofclasses = int(input("How many honors classes do you have?: "))
#List to save all grades, defined by assigning variable to []
all_grades = []
for i in range(numofclasses):
#Take grades from the user
grades = input("Enter the unweighted grade from one class ")
#Append the grades to the list, using list.append function
all_grades.append(grades)
#Loop through the list to print it
for item in all_grades:
print(item)
#Print all grades in a single line by joining all items of list in a string
s = " ".join(all_grades)
print(s)
And the output will look like
How many honors classes do you have?: 3
Enter the unweighted grade from one class A
Enter the unweighted grade from one class B
Enter the unweighted grade from one class C
#All grades in different lines
A
B
C
#All grades in single line
A B C
It seems to me there are a couple options that may be suitable.
Printing the input each iteration:
numofclasses = int(input("How many honors classes do you have?: "))
for i in range(numofclasses):
grades = str(input("Enter the unweighted grade from one class "))
print(grades) # move print to inside of loop
Storing the values in a list for printing later:
numofclasses = int(input("How many honors classes do you have?: "))
grades = []
for i in range(numofclasses):
grades.append(str(input("Enter the unweighted grade from one class ")))
print(grades) # will look like ["A", "B", "C", "B"]
Here is how yo do it:
class_dict = {}
numOfClasses = input("How many classes do you take? Enter here : ")
for i in range(int(numOfClasses)):
class_dict["class" + str(i +1)] = input("Enter your grade for class " + str(i +1) + ": ")
print(class_dict)
The above should do it.
Related
I am working on Python and am writing a program where the user inputs how many courses they would like to calculate. Then the program is supposed to take the appended items (the strings) and then divide them by how many courses they would like, in other words the total (integer). I cannot seem to figure out a way to implement this properly, any help? The issue is under If value = 1.
if (value == 1):
selection = int(input("How many classses would you like to include?\n"))
for i in range (0,selection):
print("What is the grade of the class?")
item = (input())
grades.append(item)
GPA_list = [sum(item)/selection for i in grades]
print(GPA_list)
You can simplify this quite a bit by using mean, which does the summing and dividing for you:
>>> from statistics import mean
>>> print(mean(
... float(input(
... "What is the grade of the class?\n"
... )) for _ in range(int(input(
... "How many classes would you like to include?\n"
... )))
... ))
How many classes would you like to include?
5
What is the grade of the class?
4
What is the grade of the class?
3
What is the grade of the class?
4
What is the grade of the class?
2
What is the grade of the class?
4
3.4
To fix your existing code, all you need to do is make sure to convert item to a float and then call sum on grades rather than each item:
grades = []
selection = int(input("How many classses would you like to include?\n"))
for i in range(0, selection):
print("What is the grade of the class?")
item = float(input())
grades.append(item)
GPA_list = sum(grades) / selection
print(GPA_list)
Note that your code prints a fraction of the average at each step in the loop until finally printing the correct result in the last iteration; if you want to fix this as well, unindent the last two lines.
def main():
for row in range (7):
assignment = int(1)
if row == 1:
for assignment_number in range(0,8):
assignment_number+1
for i in range(0,7):
assignment_mark = float(input(("Please enter your mark for assginment" assignment_number,": "))
assignment_weight = float(input("Please enter the total weight percentage for the assignment: "))
main()
So this is my code above,
I'm basically trying to work out how I could say for each input variable "Please enter your mark for assignment x (from 1 up to 7).
Which will loop, so once they enter it for assignment 1, it then asks the same question for assignment 2.
I hope this makes some sense. I'm new to programming in general and this just happens to also be my first post on stack! Be gentle (:
Thanks!
There are a few problems with your code:
assignment_number+1 without assigning it to a variable does nothing, and even if you did, that value would be lost after the loop. If you want to offset the numbers by one, you can just use range(1, 8) or do +1 when you actually need that value of that variable
in your second loop, your loop variable is i, but you are using assignment_number from the previous loop, which still has the value from the last execution, 7
you have to store the values for assignments_mark and assignment_weight somewhere, e.g. in two lists, a list of tuples, or a dict of tuples; since assignment numbers start with 1 and not 0, I'd recommend a dict
You can try something like this, storing the marks and weights for the assignments in a dictionary:
assignments = {}
for i in range(7):
assignment_mark = float(input("Please enter your mark for assginment %d: " % (i+1)))
assignment_weight = float(input("Please enter the total weight percentage for the assignment: "))
assignments[i+1] = (assignment_mark, assignment_weight)
print(assignments)
Let the loop do the counting, then use string formatting.
And you only need a single loop to collect each pair of events
from collections import namedtuple
Assignment = namedtuple("Assignment", "mark weight")
assignments = []
for idx in range(7):
print("Please enter data for assignment {}".format(idx+1))
mark = float(input("mark: "))
weight = float(input("weight:"))
assignments.append(Assignment(mark, weight))
print(assignments)
quarter1 = [0, "1-Course1", "2-Course2", "3-Course3", "4-Course4", "5-Course5"]
quarter2 = [0, "1-Course1", "2-Course2", "3-Course3", "4-Course4", "5-Course5"]
pick_q = int(raw_input("Pick a quarter: "))
if pick_q == 1:
assignment = 0
courses = int(raw_input("How many courses would you like to enroll? "))
print quarter1
while assignment < courses:
course = int(raw_input("Please select the course you'd like to enroll into(1-5): "))
newlist = []
chosen_assignment = quarter1[course]
newlist.append(chosen_assignment)
assignment += 1
print newlist
So I'm trying to make this program where a student can enroll to different courses within an specific quarter. I only put in 2 quarter as an example.
The problem I'm having is that I want to create a new list from the courses the student chooses, for example if he wishes Course1, 2 and 3 then a new list should be able to print "You have enrolled to [Course1,Course2, Course3]"
However when I run this and try to print the newlist it comes up when only the last pick the user entered in this case [Course3] and not with the other previous picks.
It doesn't necessarily have to print a list, but the user should be able to choose from the original list and gather this information to create new list. I put in a zero starting the list so that the user can pick a number from the list index 1-5. I'm new at python and trying to figure this thing out. Thank you in advance!!
Any other recommendations are really appreciated!!
Basically the newlist variable is being initialized again and again inside the loop. You simply need to declare it outside the loop.
quarter1 = [0, "1-Course1", "2-Course2", "3-Course3", "4-Course4", "5-ourse5"]
quarter2 = [0, "1-Course1", "2-Course2", "3-Course3", "4-Course4", "5-Course5"]
newlist = [] # Declare it outside
pick_q = int(raw_input("Pick a quarter: "))
if pick_q == 1:
assignment = 0
courses = int(raw_input("How many courses would you like to enroll? "))
print quarter1
while assignment < courses:
course = int(raw_input("Please select the course you'd like to enroll into(1-5): "))
chosen_assignment = quarter1[course]
newlist.append(chosen_assignment)
assignment += 1
print newlist
def getExamPoints(examPoints):
for examPoints in range(1, 5):
examPoints = input("Please enter students exam scores: ")
totalPoints = input("Please enter total possible points: ")
print("The total exam points are: " + sum(int(examPoints)))
avg = float(int(str(examPoints))/int(totalPoints))
print("the average is: ", avg)
on Line 5 I am getting the error 'int object is not iterable'
and I have no idea why.
I am attempting to write a program with functions and this portion of the function is suppose to take four homework scores each out of eighty points and calculate the average of the scores and then take that average and multiply it by the percentage that homework is worth for the class, but I cant even seem to get this chunk of the program to get an average of homework scores. I am not very good with python, also if this isn't formatted correctly I apologize in advance, but any help would be much appreciated.
examPoints is not a list of inputs in the original code, but just one variable that gets overwritten with each iteration of the user-input loop:
for examPoints in range(1, 5):
examPoints = input("Please enter students exam scores: ")
Instead, you want to keep each input separately.
e.g. by appending it to a list:
examPoints = []
for _ in range(1,5):
# add input to list after converting it to an integer
examPoints.append(int(input("Please enter students exam scores: ")))
...
The input-text-to-integer conversion can be done either as you are appending (return error to user immediately upon input that can't be converted), or when you're performing the sum, by using a list comprehension or the map function:
# sum version
sum([int(v) for v in examPoints])
# map version
sum(map(int, examPoints))
Sorry, but (In my opinion) your code is a bit messy. Instead, try:
def getExamPoints(examPoints):
points = []
for examPoints in range(1, 5):
points = points + [int(input("Please enter students exam scores: "))]
totalPoints = input("Please enter total possible points: ")
print("The total exam points are: " + sum(examPoints))
avg = float(int(str(examPoints))/int(totalPoints))
print("the average is: ", avg)
what sum() looks for is an iterable object, like a list, and adds together everything in it. Since examPoints is defined as an integer, it is not iterable. Instead, make a separate list, and put the input inside there.
What i have to do is have T number of test cases which is how many time i will
obtain the average of "n" number of students in each test case and i need to display the average score for each test case and the highest mark in that test case and the name of student
If you can tell me the proper way to code this and explain why it has to be that way i will greatly appreciate it! I am lost
My code:
t = int(input("enter number of cases: "))
def casing(t):
for case in range (1, t+1):
n = int(input("enter number of students: "))
def studentmarks(n):
total = 0
student = "none"
for computetotal in range(1,n+1):
student = input("please enter student name: ")
mark = int(input("please enter mark: "))
total = total+ mark
highestmark = mark
if studentmark(n) > mark:
highestmark = mark
achieve = student
return highestmark, acheive
return total, studentmark()[0], studentmark()[1]
average = float((studentmarks(n)[0])/ n)
print("average: ", average, "highest: ",studentmark(n)[1], "student: ", studentmark(n)[2])
I think the code, as it is, would be much simpler to understand and debug without the function declarations. Unless you're doing functional-style programming (e.g. passing around function objects) there's rarely a good reason to use nested functions. Here you're defining the functions, then immediately calling them once, which is fairly pointless. So here's a simplified version of your code:
t = int(input("enter number of cases: "))
for _ in range (t):
total = 0
highest_mark = 0
best_student = "none"
n = int(input("enter number of students: "))
for _ in range(n):
student = input("please enter student name: ")
mark = int(input("please enter mark: "))
total = total+ mark
if mark > highestmark:
highestmark = mark
beststudent = student
average = total / n
print("average: {}, highest: {}, student: {}"
.format(average, highestmark beststudent))
I also eliminated the function named studentmark (with no "s") which your code was calling but never defined. I'm not sure if I correctly interpreted what it was supposed to be doing, but I think so. It certainly wouldn't have worked before.
There are a few reasons this isn't working - but the root cause seems to be because your highestmark is started off in the wrong place. It looks like you later expect the student name and mark to be in a tuple, which is a good idea - but you never actually make this tuple anywhere. So, make one, and call it highest - it replaces both the student and highestmark variables. Start it as None instead of "none" (which could actually be a valid student name!), so you have above the loop:
total = 0
highest = None
and change your "is this one higher than the highest" logic to this:
if highest is None or mark > highest[1]:
highest = (name, mark)
Read as "if there is no highest student yet, or this one has a higher mark than the current highest, this one is the highest". Then you'll want the return to be:
return total, highest[0], highest[1]
But, since you only have a small amount of data (enough that it is feasible to have a user type it in at a console), then you can simplify this logic quite a bit. Read all of the data for a particular test case into a list of (student, mark) tuples, and then use Python's builtins to do the calculations:
def studentmarks(n):
marks = []
for _ in range(n):
student = input("please enter student name: ")
mark = int(input("please enter mark: "))
marks.append(student, mark)
return marks
# Calculations
marks = studentmarks(5)
print('Average: ', sum(result[1] for result in marks)/len(marks))
print('Highest: ', max(marks, key=lambda s: s[1])
Seeding it with:
>>> marks
[('Fred', 4), ('Wilma', 10), ('Barney', 8), ('Wilma', 7), ('Pebbles', 6)]
Gives an average of 7.0, and a maximum of ('Wilma', 10).