For example, the molecular weight of water (H20) is: 2(1.00794) + 15.9994 = 18
Code:
formula = int(input("Enter the number of elements: "))
for i in range(formula):
element = input("enter your element: ")
molCount = float(input("enter the molecule count: "))
print(molCount)
atomWeight = float(input("enter the atomic weight: "))
print(atomWeight)
total = molCount*atomWeight
print(total)
total = total + total
print(total)
Need help on getting multiple elements added together...
There's a mistake on the line:
total = molCount*atomWeight
You probably meant total += molCount*atomWeight instead.
Firstly, define total before your for loop. Secondly, I think your equation needs to be
total += (molCount * atomWeight)
instead of the original. Edited code:
formula = int(input("Enter the number of elements: "))
total = 0
for i in range(formula):
molCount = int(input("Enter the molecule count: "))
print("Molecule count: " + str(molCount))
atomWeight = float(input("Enter the atomic weight: "))
print("Atomic Weight: " + str(atomWeight))
total += (molCount * atomWeight)
print(total)
Related
Can someone help me identify where I went wrong with this code? I'm trying to determine the min value in my array. I collect student name, number and mark and am looking for the lowest mark.
def my_array():
students = list()
total = 0
NumStudents = int(input("Please enter number of students: "))
for i in range(int(NumStudents)):
Student_Name = input("Please enter student name: ")
students.append(Student_Name)
Student_Num = int(input("Please enter student number: "))
students.append(int(Student_Num))
Student_Mark = int(input("Please enter student mark: "))
students.append(int(Student_Mark))
total += Student_Mark
listA = students
new_list = np.array_split(listA, NumStudents)
for item in new_list:
print(list(item))
#print(list(item[0]))
print('Average Student Mark is', str(total / NumStudents))
def find_min(students):
minimum = students[0]
for x in students[1:]:
if x < minimum:
minimum = x
return minimum
find_min(students)
my_array()
but I keep getting traceback:
Traceback (most recent call last):
File "C:\Users\MMaseko\PycharmProjects\utopiaWasteDisposalPlant\iterable.py", line 37, in <module>
my_array()
File "C:\Users\MMaseko\PycharmProjects\utopiaWasteDisposalPlant\iterable.py", line 36, in my_array
find_min(students)
File "C:\Users\MMaseko\PycharmProjects\utopiaWasteDisposalPlant\iterable.py", line 33, in find_min
if x < minimum:
TypeError: '<' not supported between instances of 'int' and 'str'
Some of the values in your list are strings (student names) and some are integers (students' grades). You can't find a minimum if some of the values you are comparing aren't integers.
def my_array():
students = []
total = 0
n = int(input())
for _ in range(n):
name = input()
number = int(input())
mark = int(input())
total+=mark
students.append((mark, number, name))
return min(students)[2]
This solves your problem. There are some other parts of your code that you have, but I haven't implemented them because you didn't require it.
Here's a code that works, The find_min() function had an error due to an indentation problem with the return minimum
def my_array():
students = list()
total = 0
NumStudents = int(input("Please enter number of students: ")) #resizing array to the number of students entered by user
for i in range(int(NumStudents)): #add student info to the empty array (students = list() )
Student_Num = int(input("Please enter student number: "))
students.append(int(Student_Num))
Student_Mark = int(input("Please enter student mark: "))
students.append(int(Student_Mark))
total += Student_Mark
listA = students
new_list = np.array_split(listA, NumStudents) #spliting array to number of students as entered by user
for item in new_list:
print(list(item))
#print(list(item[0]))
print('Average Student Mark is', str(total / NumStudents))
def find_min(students): #determining lowest student mark
minimum = students[0]
for x in students[1:]:
if x < minimum:
minimum = x
return minimum
print("The lowest student mark is", str(find_min(students))) #printing lowest student mark
find_min(students)
my_array()
Your find_min function is not good. I mean if there is no element lower than the first one, it won't return anything. But even if there is one - all the others won't be considered at all - the return statement will break the loop.
The rigth way:
def find_min(students):
minimum = students[0]
for x in students[1:]:
if x < minimum:
minimum = x
return minimum
I want to make a loop where I can input numbers, and then the loop will give me the average of the numbers that I inputted. But a problem that I am facing is that I do not know how to make the loop remember the previous numbers that I inputted. I want the loop to end if I put -1.
x = (input ("enter a number: "))
while x != "-1":
y = int(input("enter another number: " ))
total = 0 + y
if total <= 0:
totally = total
print (totally)
you may use a list to store all your numbers, when you finish the input you can compute the average:
nums = []
i = int(input("enter another number: " ))
while i != -1:
nums.append(i)
i = int(input("enter another number: " ))
avg = sum(nums) / len(nums)
print(avg)
if you like one-line solution:
from statistics import mean
from itertools import takewhile, count
print(mean(takewhile(lambda x : x !=-1, (int(input()) for _ in count() ))))
if you want to print intermediary average:
nums = []
i = int(input("enter another number: " ))
while i != -1:
nums.append(i)
print(sum(nums) / len(nums))
i = int(input("enter another number: " ))
also, you could use 2 variables to hold the current sum and the total count:
i = int(input("enter another number: " ))
s = 0
c = 0
while i != -1:
c += 1
s += i
print(s / c)
i = int(input("enter another number: " ))
Probably you should define your total var before, something like this:
x = int(input ("enter a number: "))
total = x
numLoops = 1
y = 0
while y != -1:
y = int(input("enter another number: " ))
total += y # This will store the summation of y's in total var
numLoops += 1
print(f"The average is: {total/numLoops}") # Prints the average of your nums
You can do the following:
values = []
while True:
x = int(input ("enter a number: "))
if x == -1:
break
else:
values.append(x)
print(sum(values)/len(values))
Create a program that will calculate a student’s grade in a class that uses a weighted gradebook.
A weighted system uses percentages to determine how much each assignment category is worth. For this project, use the following percentages:
Project Grades = 30% (weight = .30)
Participation Grades = 20% (weight = .20)
Quizzes = 10% (weight = .10)
Exams = 40% (weight = .40)
Grading scale:
A - 90-100
B - 80-89
C - 70-79
D - 60-69
F - Below 60
Note: You will multiply the average for each of the categories by its weight. The final grade is the sum of the calculated weights.
Can't get the code to the allow the user to enter grades in all 4 categories, because it gets stuck on the first category chosen and the loop just goes on and on without stopping asking for a list of scores. I attempted a loop inside a loop, but it only continued on the first one chosen as well. Need multiple grades entered into all 4 categories which is why I need the program to allow the user to enter grades to the other categories not just the one that is chosen first.
print ("Weighted Grade Calculator ")
name = input("Enter the Student's Name ")
number = input("Enter the Student's Number ")
x = input("Enter Assignment type: ")
c = 'y'
#Loop is in case user wants to calculate another students grade
while c=='y' or c=='Y':
if x >= "quiz" or x >= "Quiz":
input_string = input("Enter a list of scores separated by space ")
#Read ints separated by spaces
lst = input_string.split()
print("Calculating sum of element of input list")
#convert strings to ints and convert map to list
lst = list(map(int, lst))
#Find total and avg
total = sum(lst)
avg_1 = total/len(lst)
elif x >= "project" or x >= "Project":
input_string = input("Enter a list of scores separated by space ")
lst = input_string.split()
print("Calculating sum of element of input list")
lst = list(map(int, lst))
total = sum(lst)
avg_2 = total/len(lst)
elif x >= "participation" or x >= "Participation":
input_string = input("Enter a list of scores separated by space ")
lst = input_string.split()
lst = list(map(int, lst))
total = sum(lst)
avg_3 = total/len(lst)
elif x >= "exam" or x >= "Exam":
input_string = input("Enter a list of scores separated by space ")
lst = input_string.split()
print("Calculating sum of element of input list")
lst = list(map(int, lst))
total = sum(lst)
avg_4 = total/len(lst)
else:
print("error, please try again")
#Finds percentage earned from each category
w_quiz = avg_1 * 0.1
w_project = avg_2 * 0.3
w_participation = avg_3 * 0.2
w_exams = avg_4 * 0.4
total = w_project + w_quiz + w_participation + w_exams
if(total >= 90 and total <=100):
grade = 'A'
elif(total >= 80 and total < 90):
grade = 'B'
elif(total >= 70 and total < 80):
grade = 'C'
elif(total >= 60 and total < 70):
grade = 'D'
elif(total >= 0 and total < 60):
grade = 'F'
print ("Student Name: " + str(name))
print ("Student ID: " + str(number))
print ("Total Weighted Score: " + str(total) + "%")
print ("Letter Grade: " + grade)
c = input("Would you like to calculate another grade? (Y or N): ")
Not sure exactly what you are looking for, but this code will take as much input as you give it and at the end will calculate the average of all totals and its respective letter grade:
def calculate_letter(total):
#function calculates letter grade
if(total >= 90 and total <=100):
grade = 'A'
elif(total >= 80 and total < 90):
grade = 'B'
elif(total >= 70 and total < 80):
grade = 'C'
elif(total >= 60 and total < 70):
grade = 'D'
elif(total >= 0 and total < 60):
grade = 'F'
return grade
print ("Weighted Grade Calculator ")
name = input("Enter the Student's Name ")
number = input("Enter the Student's Number ")
totals = [] #initialize list to append scores to
while True:
project = float(input("Enter the percentage for Projects (numbers only): "))
participation = float(input("Enter the percentage for the Participation (numbers only): "))
quizzes = float(input("Enter the percentage for Quizzes (numbers only): "))
exams = float(input("Enter the percentage for the Final Exam (numbers only): "))
w_project = project * 0.3
w_participation = participation * 0.2
w_quiz = quizzes * 0.1
w_exams = exams * 0.4
total = w_project + w_quiz + w_participation + w_exams
grade = calculate_letter(total) #running the function defined above to evaluate letter grade from total
print ("Total Weighted Score: " + str(total) + "%")
print ("Letter Grade: " + grade)
c = input("Would you like to calculate another grade? (Y or N): ").lower()
totals.append(total)
if c == 'y':
#restarts the loop
continue
else:
#exits the loop
break
print(totals)
final_averaged_score = sum(totals) / len(totals) #finding the average of the list
final_grade = calculate_letter(final_averaged_score)
print ("Student Name: " + str(name))
print ("Student ID: " + str(number))
print ("Final Averaged score: " + str(final_averaged_score))
print ("Final letter grade: " + str(final_grade))
I have a program that asks a user to enter a Student NETID and then what grades they got on 5 assignments plus the grade they got on the mid-term and final. It then adds them and divides to get that students average grade which displays in table format.
What I need to do, is loop through that whole process 9 more times. So essentially, Ill be asking 9 more students the same input, which then Ill need to display in the table format.
My question is how would I loop through the process that I have right now 'x' amount of times, then display the average of all students.
This is my code right now:
# x holds the list of grades
x = []
# count of assignments
assignments = 5
# Ask for a student ID from user
NETID = int(input('Enter your 4 digit student NET ID: '))
# fill list with grades from console input
x = [int(input('Please enter the grade you got on assignment {}: '.format(i+1))) for i in range(assignments)]
midTermGrade = int(input('Please enter the grade you got on you Mid-Term: '))
finalGrade = int(input('Please enter the grade you got on you Final: '))
# count average,
average_assignment_grade = (sum(x) + midTermGrade + finalGrade) / 7
print()
print('NET ID \t Average Final Grade')
print('---------------------------------')
for number in range(1):
print(NETID, '\t\t', format(average_assignment_grade, '.1f'),'%')
main()
And this is how it looks on console:
You really did the hardest part. I don't see why you couldn't so the loop of the average. Anyway:
student_count = 5;
A = [student_count]
for id_student in range(student_count):
print("STUDENT #", id_student+1)
# x holds the list of grades
x = []
# count of assignments
assignments = 5
# Ask for a student ID from user
NETID = int(input('Enter your 4 digit student NET ID: '))
# fill list with grades from console input
x = [int(input('Please enter the grade you got on assignment {}: '.format(i+1))) for i in range(assignments)]
midTermGrade = int(input('Please enter the grade you got on you Mid-Term: '))
finalGrade = int(input('Please enter the grade you got on you Final: '))
# count average,
average_assignment_grade = (sum(x) + midTermGrade + finalGrade) / 7
print()
print('NET ID | Average Final Grade')
print('---------------------------------')
for number in range(1):
print(NETID, " | ", format(average_assignment_grade, '.1f'),'%')
A.append(average_assignment_grade);
grades_sum = sum(A)
grades_average = grades_sum / 5;
print("SUM OF ALL STUDENTS = " + grades_sum)
print("AVERAGE OF ALL STUDENTS = " + grades_average)
Update: As suggested above, you should make a function for a single student and loop through that function in another, since SO is not a coding service I won't do that for you, but I think you got the idea.
I can't figure out how to take x (from code below) and add it to itself to get the sum and then divide it by the number of ratings. The example given in class was 4 ratings, with the numbers being 3,4,1,and 2. The average rating should be 2.5, but I can't seem to get it right!
number_of_ratings = eval(input("Enter the number of difficulty ratings as a positive integer: ")) # Get number of difficulty ratings
for i in range(number_of_ratings): # For each diffuculty rating
x = eval(input("Enter the difficulty rating as a positive integer: ")) # Get next difficulty rating
average = x/number_of_ratings
print("The average diffuculty rating is: ", average)
Your code doesn't add anything, it just overwrites x in each iteration. Adding something to a variable can be done with the += operator. Also, don't use eval:
number_of_ratings = int(input("Enter the number of difficulty ratings as a positive integer: "))
x = 0
for i in range(number_of_ratings):
x += int(input("Enter the difficulty rating as a positive integer: "))
average = x/number_of_ratings
print("The average diffuculty rating is: ", average)
try:
inp = raw_input
except NameError:
inp = input
_sum = 0.0
_num = 0
while True:
val = float(inp("Enter difficulty rating (-1 to exit): "))
if val==-1.0:
break
else:
_sum += val
_num += 1
if _num:
print "The average is {0:0.3f}".format(_sum/_num)
else:
print "No values, no average possible!"