array = []
total = 0
text = int(input("How many students in your class: "))
print("\n")
while True:
for x in range(text):
score = int(input("Input score {} : ".format(x+1)))
if score <= 0 & score >= 101:
break
print(int(input("Invalid score, please re-enter: ")))
array.append(score)
print("\n")
print("Maximum: {}".format(max(array)))
print("Minimum: {}".format(min(array)))
print("Average: {}".format(sum(array)/text))
I tried to make a python program, to validate the score, but it's still a mistake, I want to make a program if I enter a score of less than 0 it will ask to re-enter the score as well if I input more than 100. Where is my error?
Change the if statement:
array = []
total = 0
text = int(input("How many students in your class: "))
print("\n")
for x in range(text):
score = int(input("Input score {} : ".format(x+1)))
while True:
if 0 <= score <= 100:
break
score = int(input("Invalid score, please re-enter: "))
array.append(score)
print("\n")
print("Maximum: {}".format(max(array)))
print("Minimum: {}".format(min(array)))
print("Average: {}".format(sum(array)/text))
Here, the score at the same time can't be less than 0 and greater than 100. So as you want to break of the score is between 0 and 100, we use 0 <= score <= 100 as the breaking condition.
Also the loops were reversed, since you won't get what you expected to.
try this one:
array = []
total = 0
num_of_students = int(input("How many students in your class: "))
print("\n")
for x in range(num_of_students):
score = int(input("Input score {} : ".format(x + 1)))
while True:
if score < 0 or score > 100:
score = int(input("Invalid score, please re-enter: "))
else:
array.append(score)
break
print("\n")
print("Maximum: {}".format(max(array)))
print("Minimum: {}".format(min(array)))
print("Average: {}".format(sum(array)/num_of_students))
I renamed some of your variables. You should always try to using self explanatory variable names. I am also using string interpolation (should be possible for Python +3.6) and comparison chaining.
score_list = []
total = 0
number_of_students = int(input("How many students in your class: "))
print("\n")
for student in range(number_of_students):
score_invalid = True
while score_invalid:
score_student = int(input(f"Input score {student + 1} : "))
if (0 <= score_student <= 100):
score_invalid = False
else:
score_invalid = True
if score_invalid:
print("Invalid score!\n")
score_list.append(score_student)
print("\n")
print(f"Maximum: {max(score_list)}")
print(f"Minimum: {min(score_list)}")
print(f"Average: {sum(score_list) / number_of_students}")
You could try something like this:
score = -1
first_time = True
while type(score) != int or score <= 0 or score >= 101 :
if first_time:
score = int(input("Input score: "))
first_time = False
else:
score = int(input("Invalid score, please re-enter: "))
array.append(score)
Related
I wrote this for my beginner class and I don't know how to get the NAME of the SECOND STUDENT with the 2nd highest score. After testing it, I believe the code works for the first student.
I think what I need is to store the highest score in to variable high_score and then the next highest in to second_score and then compare the third score to both the highest and second score. But I am confused on how to get the name of the second highest scoring student.
num_students = int(input("enter number of students: "))
high_score = 0
high_name = ""
second_name = ""
second_score = 0
for i in range(1,num_students + 1):
if num_students < 2:
break
if num_students >= 2:
name = input("enter student name: ")
score = int(input("enter student score: "))
if score > second_score:
if score > high_score:
second_score = high_score
high_score = score
high_name = name
elif score < high_score:
second_score = score
second_name = name
print()
print("Top Two Students")
print()
print(high_name,"'s score is", high_score)
print(second_name,"'s score is", second_score)
In addition to Gary02127's solution, I'd like to point out a few other improvements:
You should move if num_students < 2 outside of your loop. It would be enough to check the condition once after the user inputted the number of students.
You could also write for i in range(num_students). It doesn't matter if the range starts with 0 or 1 since you are not using i.
Also, if you are not using a variable, you could use _ (throwaway variable) instead. See more about for _ in range(num_students) here: What is the purpose of the single underscore "_" variable in Python?.
Instead of:
if score > second_score:
if score > high_score:
# ...
else:
# ...
You could also write:
if high_score < score:
# ...
elif second_score < score:
# ...
Here is a verbose solution considering suggested improvements:
num_students = int(input("Enter number of students: "))
if num_students < 2:
exit()
highest_name = None
highest_grade = 0
second_highest_name = None
second_highest_grade = 0
for _ in range(num_students):
name = input("Enter student's name: ")
grade = int(input("Enter student's score: "))
if highest_grade < grade:
second_highest_name = highest_name
second_highest_grade = highest_grade
highest_name = name
highest_grade = grade
elif second_highest_grade < grade:
second_highest_name = name
second_highest_grade = grade
print(highest_name, highest_grade) # highest grade
print(second_highest_name, second_highest_grade) # second highest grade
You could also use a list and sorted() (built-in function):
from operator import itemgetter
num_students = int(input("Enter number of students: "))
if num_students < 2:
exit()
grades = []
for _ in range(num_students):
name = input("Enter student's name: ")
grade = int(input("Enter student's score: "))
grades.append((name, grade))
grades = sorted(grades, key=itemgetter(1), reverse=True)
print(grades[0]) # highest grade
print(grades[1]) # second highest grade
You could also use a specialized list such as SortedList (requires external package):
from sortedcontainers import SortedList
num_students = int(input("Enter number of students: "))
if num_students < 2:
exit()
grades = SortedList(key=lambda record: -record[1])
for _ in range(num_students):
name = input("Enter student's name: ")
grade = int(input("Enter student's score: "))
grades.add((name, grade))
print(grades[0]) # highest grade
print(grades[1]) # second highest grade
Notes:
Difference between sorted() and str.sort(). sorted() creates a new sorted list whereas str.sort() modifies the current list.
itemgetter(1) is equals to lambda record: record[1].
You can install SortedList with: pip install sortedcontainers.
Here's a solution based on my previous comments to your original post.
num_students = int(input("enter number of students: "))
high_score = 0
high_name = ""
second_name = ""
second_score = 0
for i in range(1,num_students + 1):
if num_students < 2:
break
# if num_students >= 2: # don't need this "if" after previous "break"
name = input("enter student name: ")
score = int(input("enter student score: "))
if score > second_score:
if score > high_score:
second_score = high_score
second_name = high_name # NEW
high_score = score
high_name = name
else: # simplified to just a plain "else:"
second_score = score
second_name = name
print()
print("Top Two Students")
print()
print(high_name,"'s score is", high_score)
print(second_name,"'s score is", second_score)
Notice that simplifying that last "elif ...:" to a simple "else:" also solves a simple bug where entering the current high score again can be ignored and not captured. If you were to run your code as is and use input values "100 80 100", you would find the 2nd high score set to 80 instead of 100.
You can simply store the details in a list. And use list.sort() to sort the values according to the score.
Here is the working code:
num_students = int(input("Enter number of students: "))
scores = []
if num_students < 2:
print('Number of students less than 2')
exit()
for i in range(num_students):
name = input("Enter student's name: ")
score = int(input("Enter student's score: "))
scores.append([name, score])
scores.sort(key=lambda details: details[1], reverse=True)
print("Top Two Students")
print()
print(f"{scores[0][0]}'s score is {scores[0][1]}")
print(f"{scores[1][0]}'s score is {scores[1][1]}")
The error I get from the program is undefined variable.
*
# Python 3.9.4
# import sys
# print(sys.version)
SubjectT = input("Enter your subject: ")
Tutor_Name = input("Enter your name: ")
Iterate = int(input("How many students are there? "))
# Set counter
# create count for each student
Accumulate = 0
for i in range(Iterate): # It will run how many time based on Iterate input
Score = float(input("Enter score: "))
Counter = True
while Counter:
if 80 <= Score < 100:
Accumulate1 = Accumulate + 1
elif 80 > Score >= 65:
Accumulate2 = Accumulate + 1
elif 65 > Score >= 50:
Accumulate3 = Accumulate + 1
elif Score < 50:
Accumulate4 = Accumulate + 1
else:
print("The number is a negative value or incorrect")
Again = input("Enter yes for restarting again or if you want to exit the program please press anything: ")
if Again in ("y", "Y", "YES", "Yes", "yes"):
continue
else:
break
print(f"Subject title:", {SubjectT}, "\nTutor:", {Tutor_Name})
print("Grade", " Number of students")
print("A", "Students: ", Accumulate1)
print("B", "Students: ", Accumulate2)
print("C", "Students: ", Accumulate3)
print("D", "Students: ", Accumulate4)
This is my first post in Stackoverflow.
pardon me for any inappropriate content.
Thanks you so much.
You stated
Counter = True
without iteration, thus it will run indefinitely. With while loop you need to set some constraints.
I realised why you had the While loop in there, but it still wasn't working for me effectively - if all answers were within range it never terminated. This should work for you, it does for me. I changed it so it checks every time somebody enters a score that it is within the correct range, so you don't have to repeat the whole loop in the event of incorrect values
SubjectT = input("Enter your subject: ")
Tutor_Name = input("Enter your name: ")
NoOfStudents = int(input("How many students are there? "))
# Set counter
# create count for each student
Accumulate = 0
Accumulate1 = 0
Accumulate2 = 0
Accumulate3 = 0
Accumulate4 = 0
def validRange(score):
if 0 <= score <=100:
return True
else:
return False
i = 1
while (i <= NoOfStudents): # It will run how many time based on Iterate
validInput = False
while (not validInput):
Score = float(input("Enter score: "))
if ( not validRange(Score)):
print("The number is a negative value or incorrect")
else:
validInput = True
if 80 <= Score < 100:
Accumulate1 = Accumulate1 + 1
elif 80 > Score >= 65:
Accumulate2 = Accumulate2 + 1
elif 65 > Score >= 50:
Accumulate3 = Accumulate3 + 1
elif Score < 50:
Accumulate4 = Accumulate4 + 1
i = i+1
print(f"Subject title:", {SubjectT}, "\nTutor:", {Tutor_Name})
print("Grade", " Number of students")
print("A", "Students: ", Accumulate1)
print("B", "Students: ", Accumulate2)
print("C", "Students: ", Accumulate3)
print("D", "Students: ", Accumulate4)
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.
I'm having trouble because I'm asking the user to input 6 numbers into a list and then total and average it depending on input from user. It's my HWK. Please help.
x = 0
list = []
while x < 6:
user = int(input("Enter a number"))
list.append(user)
x = x + 1
numb = input("Do you want a total or average of numbers?")
numb1 = numb.lower
if numb1 == "total":
Here is my answer:
def numberTest():
global x, y, z
L1 = []
x = 0
y = 6
z = 1
while(x < 6):
try:
user = int(input("Enter {0} more number(s)".format(y)))
print("Your entered the number {0}".format(user))
x += 1
y -= 1
L1.append(user)
except ValueError:
print("That isn't a number please try again.")
while(z > 0):
numb = input("Type \"total\" for the total and \"average\"").lower()
if(numb == "total"):
a = sum(L1)
print("Your total is {0}".format(a))
z = 0
elif(numb == "average"):
b = sum(L1)/ len(L1)
print("Your average is {0}".format(round(b)))
z = 0
else:
print("Please try typing either \"total\" or \"average\".")
numberTest()
I tried this a couple of times and I know it works. If you are confused about parts of the code, I will add comments and answer further questions.
here is my current code:
total = 0.0
count = 0
data = input("Enter a number or enter to quit: ")
while data != "":
count += 1
number = float(data)
total += number
data = input("Enter a number or enter to quit: ")
average = total / count
if data > 100:
print("error in value")
elif data < 0:
print("error in value")
elif data == "":
print("These", count, "scores average as: ", average)
The only problem now is "expected an indent block"
I would do something cool like
my_list = list(iter(lambda: int(input('Enter Number?')), 999)) # Thanks JonClements!!
print sum(my_list)
print sum(my_list)/float(len(my_list))
if you wanted to do conditions, something like this would work
def getNum():
val = int(input("Enter Number"))
assert 0 < val < 100 or val == 999, "Number Out Of Range!"
return val
my_list = list(iter(getNum, 999)) # Thanks JonClements!!
print sum(my_list)
print sum(my_list)/float(len(my_list))
To calculate an average you will need to keep track of the number of elements (iterations of the while loop), and then divide the sum by that number when you are done:
total = 0.0
count = 0
data = input("Enter a number or enter 999 to quit: ")
while data != "999":
count += 1
number = float(data)
total += number
data = input("Enter a number or enter 999 to quit: ")
average = total / count
print("The average is", average)
Note that I renamed sum to total because sum is the name of a built-in function.
total = 0.0
count = 0
while True:
data = input("Enter a number or enter 999 to quit: ")
if data == "999":
break
count += 1
total += float(data)
print(total / count)