Average of marks for three topics - python

I am trying to create a program that will ask the user for a username and password. If the login details are correct, the program should ask for the students name and then ask for three scores, one for each topic. The program should ask the user if they wish to enter another students details. The program should output the average score for each topic. I cannot work out how to enter the student marks for each topic per student and also how to work out the average for each topic for the class.
Can you please help?
login="teacher"
password="school"
usrnm=input("Please enter your username: ")
pw=input("Please enter your password: ")
if (usrnm==login) and (pw==password):
print("==Welcome to the Mathematics Score Entry Program==")
print("Do you want to enter the students score? Yes/No: ")
option = input()
option = option.title()
student_info = {}
student_data = ['Topic 1 : ', 'Topic 2 : ', 'Topic 3 : ']
while (option != "No"):
student_name = input("Name: ")
student_info[student_name] = {}
score1 = int(input("Please enter the score for topic 1: "))
student_info[student_name][Topic_1] = score1
score2 = int(input("Please enter the score for topic 2: "))
student_info[student_name][Topic_2] = score2
score3 = int(input("Please enter the score for topic 3: "))
student_info[student_name][Topic_3] = score3
print("Do you want to enter the students score? Yes/No: ")
option = input()
option = option.title()
average = sum(student_info.values())/len(student_info)
average = round(average,2)
print ("The average score is ", average)
else:
print("Access denied!")

just keep the marks seperate from the student names
students = []
marks = []
option = ""
while (option != "No"):
students.append(input("Name"))
marks.append([float(input("Mark_Category1:")),
float(input("Mark_Category2:")),
float(input("Mark_Category3:"))])
option = input("Add Another?")
import numpy
print(numpy.average(marks,0))
if you really want to do it without numpy
averages = [sum(a)/float(len(a)) for a in zip(*marks)] # transpose our marks and average each column

Related

Unable to pass/exit a python function

Just starting out with python functions (fun_movies in functions.py) and I can't seem to get out (via "no" or False) once in the loop:
main_menu.py
from functions import *
def menu():
print("Press 1 for movies.")
print("Press 2 to exit.")
menu()
option = int(input("Input a number: "))
while option != 0:
#try:
if option == 1:
fun_movies()
elif option == 2:
print("Goodbye! ")
break
else:
print ("Wrong input")
functions.py
global movies
movies = {}
def fun_movies():
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies [name] = [genre]
a = True
while a:
query = input("Do you want to input another movie? (yes/no) ")
if query == "yes":
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies_if = {}
movies_if [name] = [genre]
movies.update(movies_if)
elif query == "no":
break
else:
print ("Wrong input!")
return movies
Code works fine when not called via import. When called via import (in main_menu.py), it keeps asking for infinite movies even when I input a "no". I can't find a way to exit the loop. Initially I had a "pass" but that didn't work.
Thanks in advance!
global movies
movies = {}
def fun_movies():
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies [name] = [genre]
a = True
while a:
query = input("Do you want to input another movie? (yes/no) ")
if query == "yes":
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies_if = {}
movies_if [name] = [genre]
movies.update(movies_if)
elif query == "no":
a = False
else:
print ("Wrong input!")
return movies
A few things:
Firstly, you don't need a==True as this statement returns True when a is True and False when a is False, so we can just use a as the condition.
Secondly, only use the input at the start of the loop as you want to ask once per iteration
Thirdly, place your return outside the loop so you only return when a==False and you don't want to input another movie.
edit:
main file>
from functions import *
def menu():
print("Press 1 for movies.")
print("Press 2 to exit.")
menu()
option = int(input("Input a number: "))
while option != 0:
if option == 1:
fun_movies()
elif option == 2:
print("Goodbye! ")
break
else:
print ("Wrong input")
option = int(input("Input a number"))
global movies
movies = {}
def fun_movies():
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies[name]= genre
a = True
while a:
query = input("Do you want to input another movie? (yes/no) ")
if query == "yes":
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies_if = {}
movies_if [name] = genre
movies.update(movies_if)
elif query == "no":
break
else:
print ("Wrong input!")
# continue
return movies
print(fun_movies())
Hope It works for you!

How can I print the report without the first in the list

I'm trying to display the names except the 'name' and trying to get the average of age without 'age' on the list and lastly get the average of the grade without the 'Grade'.
I have a problem I'm trying to print the names of the list without the first row in the list(['Name', 'Age', 'Grade']) without pop or removing them from the list.
studentDB = [['Name', 'Age', 'Grade'], ['Con', 20, 90.2],
['Juan', 45, 70.2], ['Jed', 39, 100.0]]
while True:
for i in range(len(studentDB)):
print(i, studentDB[i])
print("\n********** Hackathon ***********")
CRUD = """1- Add
2- Delete
3- Edit
4- Print Report
----------------
Enter a number: """
choice = float(input(CRUD))
if (choice == 1):
Name = input("Please Enter your Name: ")
Age = int(input("Please Enter your Age: "))
Grade = float(input("Please Enter your Grade: "))
studentDB.append([Name, Age, Grade])
print(studentDB)
elif (choice == 2):
Del = int(input("Please Enter the row you want to delete: "))
studentDB.pop(Del)
elif (choice == 3):
Del1 = int(input("Please Enter the row you want to delete: "))
Name1 = input("Please Enter your Name: ")
Age1 = int(input("Please Enter your Age: "))
Grade1 = float(input("Please Enter your Grade: "))
studentDB.pop(Del1)
studentDB.insert(Del1,[Name1, Age1, Grade1])
print(studentDB)
elif (choice == 4):
#here is the problem
for s in range(1, len(studentDB)):
print("")
print(f"There are in the {s} student table. The people included in the list are.")
else:
print("Invalid input")
Here is the output that I wanted to do
This is the online compiler: https://www.programiz.com/python-programming/online-compiler/
There can be many ways to solve this. One could be to use starting index in range and use slice while calculating average of age or grades.
from statistics import mean
while True:
# Use the start index in range.
for i in range(len(studentDB)):
print(i, studentDB[i])
print("\n********** Hackathon ***********")
CRUD = """1- Add
2- Delete
3- Edit
4- Print Report
----------------
Enter a number: """
choice = float(input(CRUD))
if (choice == 1):
Name = input("Please Enter your Name: ")
Age = int(input("Please Enter your Age: "))
Grade = float(input("Please Enter your Grade: "))
studentDB.append([Name, Age, Grade])
print(studentDB)
elif (choice == 2):
Del = int(input("Please Enter the row you want to delete: "))
studentDB.pop(Del)
elif (choice == 3):
Del1 = int(input("Please Enter the row you want to delete: "))
Name1 = input("Please Enter your Name: ")
Age1 = int(input("Please Enter your Age: "))
Grade1 = float(input("Please Enter your Grade: "))
studentDB.pop(Del1)
studentDB.insert(Del1,[Name1, Age1, Grade1])
print(studentDB)
elif (choice == 4):
#here is the problem
# Use slice to get the row from index 1 afterwards
print(f"There are in the {len(studentDB) - 1} records in the student table. The people included in the list are.")
print(",".join([student[0] for student in studentDB[1:]]))
average_age = mean([row[1] for row in studentDB[1:]])
average_grades = mean([row[2] for row in studentDB[1:]])
# Print average age and grades here
else:
print("Invalid input")```

Can't figure out this For loop in Python

I'm trying to get this For loop to repeat itself for an amount equal to "totalNumStudents"
for score in range(totalNumStudents):
# Prompt to enter a test score.
test_score = int(input("Enter the test score: "))
# If the test score entered is in range 0 to
# 100, then break the loop.
if 0 <= test_score <= 100:
break
However, the code never gets to this loop and restarts from the beginning.
Here is the first half of the code including the loop.
freshman = 0
sophomore = 0
junior = 0
senior = 0
test_score = 0
totalTestScores = 0
totalNumStudents = freshman + sophomore + junior + senior
# Start a while loop.
while True:
# Display the menu of choices.
print("\nPress '1' to enter a student")
print("Press '2' to quit the program")
print("NOTE: Pressing 2 will calculate your inputs.\n")
# Prompt to enter a choice.
choice = input("Enter your choice: ")
# If the choice is 1.
if choice == '1':
# Start a while loop to validate the grade level
while True:
# Prompt the user to enter the required grade level.
freshman = int(input("How many students are Freshman? "))
sophomore = int(input("How many students are Sophomores? "))
junior = int(input("How many students are Juniors? "))
senior = int(input("How many students are Seniors? "))
break
for score in range(totalNumStudents):
# Prompt to enter a test score.
test_score = int(input("Enter the test score: "))
# If the test score entered is in range 0 to
# 100, then break the loop.
if 0 <= test_score <= 100:
break
# Otherwise, display an error message.
else:
print("Invalid test score! Test score " +
"must be between 0 and 100.")
# Calculate total test scores
totalTestScores = totalTestScores + test_score
What am I missing here?
Since you add up before get those numbers, your totalNumStudents is all always zero. You should put the add up statement after you get the numbers:
...
# Start a while loop to validate the grade level
while True:
# Prompt the user to enter the required grade level.
freshman = int(input("How many students are Freshman? "))
sophomore = int(input("How many students are Sophomores? "))
junior = int(input("How many students are Juniors? "))
senior = int(input("How many students are Seniors? "))
break
# add up here
totalNumStudents = freshman + sophomore + junior + senior
for score in range(totalNumStudents):
# Prompt to enter a test score.
test_score = int(input("Enter the test score: "))
# If the test score entered is in range 0 to
# 100, then break the loop.
if 0 <= test_score <= 100:
break
...
BTW since your while True loop only runs once, you don't need the loop. Just remove it.

Create a vector given N input of names and ages python

I need to create a program that takes as inputs multiple entries of names and ages. Then I want it to return the names and ages of those entries that have higher age values than the average age of all entries.
For example:
input( "Enter a name: ") Albert
input( "Enter an age: ") 16
input( "Enter a name: ") Robert
input( "Enter an age: ") 18
input( "Enter a name: ") Rose
input( "Enter an age: ") 20
The average is = 18
Rose at 20 is higher than the average.
How can I do this?
answers = {}
# Use a flag to indicate that the questionnaire is active.
questions_active = True
while questions_active:
# Ask for the person's name and response.
name = raw_input("\nEnter a name: ")
response = raw_input("Enter an age: ")
# Store the response in the dictionary:
answers[name] = int(response)
# Check if anyone else is going to take the questionnaire.
repeat = raw_input("Would you like to let another person respond? (yes/ no) ")
if repeat == 'no':
questions_active = False
average_age = sum(answers.values())/float(len(answers))
print("The average is " + str(average_age))
# Questionnaire is complete. Show the results.
for name, response in answers.items():
if response > average_age:
print(name.title() + " at " + str(response) + " is higher than the average.")
This answer is based on a similar example from the book "Python Crash Course: A Hands-On, Project-Based Introduction to Programming" https://www.nostarch.com/pythoncrashcourse

Why do I get an invalid syntax error in this piece of code, Python?

Code:
students = []
choice = None
while choice != 0:
print(
"""
0 - Exit
1 - Show all students
2 - Add a student
"""
)
choice = input("Choice: ")
print()
if choice == "0":
print("Goodbye")
break
elif choice == "1":
print("\nStudents: ")
for entry in students:
email, name, number = entry
print(name, "\t", email, "\t", number)
elif choice == "2":
name = input("What is the students name?")
email = input("What is the students email adress? ")
number = int(input("What is the students number? ")
entry = email, name, number
students.append(info)
students.sort(reverse=False)
student = students
else:
print("Sorry, but", choice, "isn't a valid choice.")
When I run this in the compiler, I get a syntax error for the line
entry = email, name, number
I don't know why, please tell me.
You have a missing ) on the line immediately above the line of the error.
number = int(input("What is the students number? ") #here
entry = email, name, number
In general, missing parentheses cause the stack trace to point to the line immediately following.

Categories

Resources