I want my program to take any number of scores from any number of students, and run calculations on them.
student_number = 1
try:
score = int(input("Please enter Student " + str(student_number) + "'s score (-1: Exit): "))
except:
print("The score entered is not a number. Please enter it again.")
score = int(input("Please enter Student " + str(student_number) + "'s score (-1: Exit): "))
while score != -1:
try:
score = int(input("Please enter Student " + str(student_number) + "'s score (-1: Exit): "))
except:
print("The score entered is not a number. Please enter it again.")
score = int(input("Please enter Student " + str(student_number) + "'s score (-1: Exit): "))
more_student = input("Any more student? (Yes or No): ")
while more_student == "Yes":
student_number = student_number + 1
try:
score = int(input("Please enter Student " + str(student_number) + "'s score (-1: Exit): "))
except:
print("The score entered is not a number. Please enter it again.")
score = int(input("Please enter Student " + str(student_number) + "'s score (-1: Exit): "))
while score != -1:
score = int(input("Please enter Student " + str(student_number) + "'s score (-1: Exit): "))
more_student = input("Any more student? (Yes or No): ")
print("done")
Instead of print("done"), I want to somehow take every input I have received and be able to split it up by student, example output:
Student _ has 4 scores. Their average score is _.
Student _ has 3 scores. Their average score is _.
i'd use a dictionary i guess ? This will allow to collect data for each student, namely.
scores = {}
student = input("Student ? ") # Ask for student
if(student not in scores.keys()): # Create new student if necessary
scores[student] = []
score = int(input("Score ? ")) # Generate & store score for the student
scores[student].append(score)
Then to compute for each student the mean of the scores ... So many possibilities. The easiest one to me:
for student, score_list in scores.items():
nb_scores = len(score_list)
mean_score = sum(score_list)/len(score_list)
print("Student {} had {} scores, with a mean of {}". format(student, nb_scores, mean_score))
I'd just finished typing this up for another question of yours that got deleted -- it looks like the same basic problem as this one.
The approach in a nutshell (as I see the accepted answer to this version of the question is already doing) is to use two nested loops, breaking them when it's time to go to the outer loop.
scores = []
while True:
scores.append([])
while True:
try:
score = int(input(
f"Please enter Student {len(scores)}'s score (-1: Exit): "
))
if score == -1:
break
scores[-1].append(score)
except ValueError:
print("The score entered is not a number. Please enter it again.")
if input("Any more student? (Yes or No): ").lower() != "yes":
break
print(scores)
Please enter Student 1's score (-1: Exit): 78
Please enter Student 1's score (-1: Exit): 34
Please enter Student 1's score (-1: Exit): -1
Any more student? (Yes or No): yes
Please enter Student 2's score (-1: Exit): 45
Please enter Student 2's score (-1: Exit): -1
Any more student? (Yes or No): No
[[78, 34], [45]]
I included two infinite loops that breaks when -1 is entered. A hashmap is used where every Student ID is a key and is initialized with an empty array that stores the marks as the second loop executes itself.
marks = {}
while True:
i = int(input("Enter Student ID or press -1 to exit"))
if i == -1:
break
else:
marks[i] = []
while True:
x = int(input("Enter Mark or press -1 to exit"))
if x!=-1:
marks[i].append(x)
else:
break
for i in marks.keys():
count = len(marks[i])
avg = sum(marks[i])/count
print("Student {} has {} scores. Their average is {}".format(i, count, avg))
Related
i tried everything shoould i add something in between or what i used to work with c++
so i dont know what to do
print("1 add")
print("2 sub")
print("3 mult")
print("4 div")
start = int(input("please choose what u want: "))
if start == "1":
print("enter your first number")
choose = float(input("please enter your first number: "))
chose = float(input("please enter your second number: "))
print("your answer is ", (choose + chose))
if start == "2":
print("enter your first number")
choose = float(input("please enter your first number: "))
chose = float(input("please enter your second number: "))
print("your answer is ", (choose - chose))
If I understood correctly, you have an indentation problem, as well as condition one.
Every input from the console is treated as a string.
You converted that input to int and then checked against the string, it isn't equal.
The right one would be:
start = input("please choose what u want: ")
if start == "1":
or
start = int(input("please choose what u want: "))
if start == 1:
Also, make sure to indent the code:
if start == "2":
print("enter your first number")
choose = float(input("please enter your first number: "))
chose = float(input("please enter your second number: "))
print("your answer is ", (choose - chose))
You should write your code inside the if statement like this:
start = int(input("please choose what u want: "))
if start == 1:
print("enter your first number")
choose = float(input("please enter
your first number: "))
chose = float(input("please enter
your second number: "))
print("your answer is ", (
choose+chose))
if start == 2:
print("enter your first number")
choose = float(input("please enter
your first number: "))
chose = float(input("please enter
your second number: "))
print("your answer is ", (choose -
chose))
Try:
print("1 add")
print("2 sub")
print("3 mult")
print("4 div")
start = int(input("please choose what u want: "))
if start == 1:
print("enter your first number")
choose = float(input("please enter your first number: "))
chose = float(input("please enter your second number: "))
print("your answer is ", (choose + chose))
elif start == 2:
print("enter your first number")
choose = float(input("please enter your first number: "))
chose = float(input("please enter your second number: "))
print("your answer is ", (choose - chose))
The data you get from the user is integer, but the type you are querying is string. Your code is not working due to data type mismatch. I have specified the correct code above.
Where am I going wrong, the first part does exactly what I want. I put the first student in with scores it converts and averages but after repeat, it combines the lists and averages ofoutput all subsequent students.
def determine_grade(score):
if (score > 89):
return "A"
elif (score > 79):
return "B"
elif (score > 69):
return "C"
elif (score > 59):
return "D"
elif (score <= 59):
return "F"
def calc_average(test_scores):
total = 0
for i in range(len(test_scores)):
total = total + test_scores[i]
return total/int(len(test_scores))
def main():
repeat="yes"
test_scores = []
while repeat.lower() == "yes":
student = input("\nEnter student name: ")
for i in range(2):
score = round(float(input("Enter score: ")))
test_scores.append(score)
average_score = calc_average(test_scores)
print("\nStudent Name: ", student)
for i in range(len(test_scores)):
print("Score: ",test_scores[i], "Grade: ",determine_grade(test_scores[i]))
print("Average: ", average_score, "Student: ",student)
repeat = input("\nEnter anther student? yes or no: ")
main()
The thing that is wrong with this piece of code is that when you finished collecting info from one student the info is still left in the list, and was mixed up with another student's info
def main():
repeat="yes"
test_scores = []
while repeat.lower() == "yes":
test_scores.clear()
student = input("\nEnter student name: ")
for i in range(2):
score = round(float(input("Enter score: ")))
test_scores.append(score)
average_score = calc_average(test_scores)
print("\nStudent Name: ", student)
for i in range(len(test_scores)):
print("Score: ",test_scores[i], "Grade: ",determine_grade(test_scores[i]))
print("Average: ", average_score, "Student: ",student)
repeat = input("\nEnter another student? yes or no: ")
main()
You need to clear the list before collecting again.
After this line:
while repeat.lower() == "yes":
put:
print(test_scores)
Run the script and enter marks for a couple of students.
I think you will see why it is summing all the students marks in one go.
By the way, sum(test_scores) will add up the elements of test_scores for you. No need
for a loop. Also try out:
for score in test_scores:
print(score)
In general, when you are tempted to write
for i in range(len(things)):
followed by
things[i]
inside the loop, it is usually easier to write
for thing in things:
do_something_with(thing)
Your code will be shorter, more readable and more efficient.
Replace your main fucntion with this one:
def main():
repeat="yes"
while repeat.lower() == "yes":
test_scores = [] # Inside the while loop so it is new every time
student = input("\nEnter student name: ")
for i in range(2):
score = round(float(input("Enter score: ")))
test_scores.append(score)
average_score = calc_average(test_scores)
print("\nStudent Name: ", student)
for i in range(len(test_scores)):
print("Score: ",test_scores[i], "Grade: ",determine_grade(test_scores[i]))
print("Average: ", average_score, "Student: ",student)
repeat = input("\nEnter anther student? yes or no: ")
This is a three part question that I am having issues with....
My output is not giving me the option to input my integer, it is printing "none" on the following line and skipping the option
Ending the file trigger is not working properly
counting the players that I have recorded data for....I honestly don't know where to start on counting inputs
--------------------My Output----------------------
You will be asked to enter players names and scores
When you have no more names, enter End
Enter Player's Name or End to exit program: Randy
Enter Randy 's golf score:
None
------------------My Output END--------------------
My code;
def main():
#introduction to user explaining required information to be entered
print("You will be asked to enter players names and scores")
print("When you have no more names, enter End")
#double blank space
print("\n")
#defined y/n
anotherPlayer = "y"
#define file path to save user input
usersFile = open('golf.txt', 'w')
#
while anotherPlayer == "y":
playerName = input("Enter Player's Name or End to exit program: ")
score = int(input(print("Enter", playerName, "'s golf score: ")))
usersFile.write(playerName + "," + str(score) + "\n")
anotherPlayer = input("Is there another player? y / End: ")
End = usersFile.close()
main()
-----------------end my code--------------------
I need it to say;
---------Assignment output Needed-----------------
You will be asked to enter players names and scores
When you have no more names, enter End
Enter Player's Name or End to exit program: Randy
Enter Randy 's golf score: 50
Enter Player's Name or End to exit program: End
You have written 1 players records to golf.txt
---------End assignment output----------------
Try this:
def main():
# introduction to user explaining required information to be entered
print("You will be asked to enter players names and scores")
print("When you have no more names, enter End")
# double blank space
print("\n")
# defined y/n
anotherPlayer = "y"
# define file path to save user input
usersFile = open('golf.txt', 'w')
#
while anotherPlayer == "y":
playerName = raw_input("Enter Player's Name or End to exit program: ")
score=input("Enter "+ str(playerName)+"'s golf score: ")
usersFile.write(playerName + "," + str(score) + "\n")
anotherPlayer = raw_input("Is there another player? y / End: ")
End = usersFile.close()
main()
You don't need to use print here.
score = int(input(print("Enter", playerName, "'s golf score: ")))
Use this
score = int(input("Enter {}'s golf score: ".format(playerName)))
score = int(input(print("Enter", playerName, "'s golf score: ")))
Should be changed to
score = int(input("Enter {0}'s golf score: ".format(playerName)))
for opening and closing a file in python the efficient method is as follows:
with open("filename", "w") as userFile:
userFile.write(data)
using the with open method will close the file for you when the loop is complete.
You have a problem in the line
score = int(input(print("Enter", playerName, "'s golf score: ")))
You cant put a print function inside the input function and you also can not do it like this:
score = int(input("Enter", playerName, "'s golf score: "))
Because input does not work the same way print does. You should read about formatting in python and do it like this:
score = int(input("Enter {0}'s golf score: ".format(playerName)))
I'm working on a homework assignment for my game dev. class and I can't quite figure out what I'm doing wrong. I am trying to add numbers to a high score that has already been hardwired in by the use of user input. For example; Trying to add 100 points to Roger who currently has 3456 points. I just haven't quite figured out what I'm doing wrong to get the code to work. All and any help is very appreciated. Thank you.
str1 = ["Roger", 3456]
str2 = ["Justin", 2320]
str3 = ["Beth", 1422]
enter = 0
start = 0
Roger = ()
def incdec(sco):
return addit
def addition(num1):
return num1 + num1
def square(num):
print("I'm in square")
return num * num
def display(message):
"""Display game instuctions"""
print(message)
def instructions():
"""Display game instuctions"""
print("Welcome to the world's greatest game")
def main():
instructions()
scores = [str1, str2, str3]
start = input("Would you like to view the high score options? y/n ")
if start == "y":
print("""\
Hello! Welcome to the high scores!
Here are the current high score leaders!:
""")
print(scores)
print("""\n\
0 - Sort high scores
1 - Add high score
2 - Reverse the order
3 - Remove a score
4 - Square a number
5 - Add 2 numbers together
6 - Add to a score
7 - Subtract from a score
""")
option = int(input("Please enter your selection "))
while option < 8:
print(scores)
if option == 0:
scores.sort()
print("These are the scores sorted alphabetically")
print(scores)
option = option = int(input("Please enter your selection"))
elif option == 1:
print(scores)
print("Please enter your name and score; After entering your name, hit the return key and enter your score")
name = input()
score = int(input())
entry = (name,score)
scores.append(entry)
print(scores)
option = option = int(input("Please enter your selection"))
elif option == 2:
print(scores)
scores.reverse()
print("\nHere are the scores reversed")
print(scores)
option = option = int(input("Please enter your selection"))
elif option == 3:
print(scores)
print("Please enter the high score you would like to remove. After typing the name, hit the return key and enter the score")
name1 = input()
score1 = int(input())
remove = (name1,score1)
scores.remove(remove)
print(scores)
option = option = int(input("Please enter your selection"))
elif option == 4:
val = int(input("Give me a number to square"))
sqd = square(val)
print(sqd)
option = option = int(input("Please enter your selection"))
elif option == 5:
val0 = int(input("Give me one number"))
val1 = int(input("Give me another number"))
addi = (val0 + val1)
print(addi)
option = option = int(input("Please enter your selection"))
elif option == 6:
sc0 = input("Please enter the person whose score you would like to add to ")
sc1 = int(input("Please enter the amount you would like to add to their score "))
addit =(sc0 + str(sc1))
print(addit)
option = option = int(input("Please enter your selection"))
elif option == 7:
break
main()
You're adding a number to a string. What you need to do is search for the player in your scores list and then add the given number to their current score. Using your current structure, you could do the following:
def update_score(scores, person, amount):
# Loop through the current scores
for score in scores:
# Find the person we're looking for
if score[0].lower() == person.lower():
# Update their score
score[1] += amount
return scores
And then modify as such:
...
elif option == 6:
sc0 = input("Please enter the person whose score you would like to add to ")
sc1 = int(input("Please enter the amount you would like to add to their score "))
scores = update_score(scores, sc0, sc1)
print(scores)
option = option = int(input("Please enter your selection"))
...
Which produced for me:
Please enter the person whose score you would like to add to roger
Please enter the amount you would like to add to their score 100
[['Roger', 3556], ['Justin', 2320], ['Beth', 1422]]
However, I would refactor a lot of the boilerplate away and use dictionary lookups for tracking players. But the above solution solves your stated problem.
Im new to python and I am currently working on a python script and want to add a loop at the end of it, currently the code is as follows:
#FinalGrade
print ("\n")
Institution = str(input("Please Enter the Name of Your insitution: "))
print ("\n")
Year = str(input("Please Enter the Year of the Student (For Example, 'Year 2'): "))
print ("\n")
Student = str(input("Student Full Name: "))
print ("\n")
Grade1 = int(input("Enter Student's First Term Grade: "))
Grade2 = int(input("Enter Student's Second Term Grade: "))
Grade3 = int(input("Enter Student's Third Term Grade: "))
Grade4 = int(input("Enter Student's Fourth Term Grade: "))
average = (Grade1+Grade2+Grade3+Grade4)/4
print ("\n")
print ("Total Grade Average: %G" % (average))
passed_or_failed = "PASSED"
if average < 40:
passed_or_failed = 'FAILED'
print ("\n")
print ("%s has: %s" % (Student, passed_or_failed))
Id like to find out if it would be possible to set a loop so another student can be entered, would this be possible?
Thank you
Why not put it in an infinite loop?
cont = 'y'
while cont=='y':
print ("\n")
Institution = str(input("Please Enter the Name of Your insitution: "))
print ("\n")
Year = str(input("Please Enter the Year of the Student (For Example, 'Year 2'): "))
print ("\n")
Student = str(input("Student Full Name: "))
print ("\n")
Grade1 = int(input("Enter Student's First Term Grade: "))
Grade2 = int(input("Enter Student's Second Term Grade: "))
Grade3 = int(input("Enter Student's Third Term Grade: "))
Grade4 = int(input("Enter Student's Fourth Term Grade: "))
average = (Grade1+Grade2+Grade3+Grade4)/4
...
cont = input('Do you want to keep entering students? y/n: ')
Or if you want to keep all of the results:
results = []
cont = 'y'
while cont=='y':
print ("\n")
Institution = str(input("Please Enter the Name of Your insitution: "))
...
passed_or_failed = "PASSED"
if average < 40:
passed_or_failed = 'FAILED'
results.append(passed_or_failed)
...
cont = input('Do you want to keep entering students? y/n: ')
And you can just loop through the results to see them.
You mean just one more student to be entered?
You can probably do that with a while or for loop. Something along these lines:
counter = 0
while (counter < 2):
your existing code
....
counter += 1