Every time I run the code I get "TypeError: 'int' object is not iterable".
So my question is: How do I print/use the min and max function at the end? So if someone let's say types 5,7,10, and -1. How do I let the user know that the highest score is 10 and the lowest score would be 5? (And then I guess organizing it from highest numbers to lowest.)
def fillList():
myList = []
return myList
studentNumber = 0
myList = []
testScore = int(input ("Please enter a test score "))
while testScore > -1:
# myList = fillList()
myList.append (testScore)
studentNumber += 1
testScore = int(input ("Please enter a test score "))
print ("")
print ("{:s} {:<5d}".format("Number of students", studentNumber))
print ("")
print ("{:s} ".format("Highest Score"))
print ("")
high = max(testScore)
print ("Lowest score")
print ("")
print ("Average score")
print ("")
print ("Scores, from highest to lowest")
print ("")
Your problem is that testScore is an integer. What else could it be? Each time through the list, you reassign it to the next integer.
If you want to, say, append them to a list, you have to actually do that:
testScores = []
while testScore > -1:
testScores.append(testScore)
# rest of your code
And now it's easy:
high = max(testScores)
And, in fact, you are doing that in the edited version of your code: myList has all of the testScore values in it. So, just use it:
high = max(myList)
But really, if you think about it, it's just as easy to keep a "running max" as you go along:
high = testScore
while testScore > -1:
if testScore > high:
high = testScore
# rest of your code
You will get different behavior in the case where the user never enters any test scores (the first one will raise a TypeError about asking for the max of an empty list, the second will give you -1), but either of those is easy to change once you decide what you actually want to happen.
If all your scores are in a array.
print("The max was: ",max(array))
print("The min was: ",min(array))
Related
I want to make an calculator for average but i'm facing some issues. I want the numbers entered by the users come as a print statement but it is just throwing the last entered value.Here is my code.
numlist = list()
while True:
inp = input(f"Enter a number, (Enter done to begin calculation): ")
if inp == 'done':
break
value = float(inp)
numlist.append(value)
average = sum(numlist) / len(numlist)
print(f"The Entered numbers are: ", inp)
print(f"average is = ", average)
Solution
we can print the list
numlist = list()
while True:
inp = input(f"Enter a number, (Enter done to begin calculation): ")
if inp == 'done':
break
value = float(inp)
numlist.append(value)
average = sum(numlist) / len(numlist)
print(f"The Entered numbers are: {numlist}")
print(f"average is = ", average)
As I understand, you want to print all the user inputs, however, as I see in your code, you are printing just a value but not the storing list, try to change your code to print(f"The Entered numbers are: ", numlist)
You are telling the user that their entered numbers are the last thing they typed in input, which will always be "done" because that is what breaks out of the loop. If you want to print the entered numbers; print numlist instead of inp.
For some reason the print command at the bottom is not printing out it is just looping no matter how I put indentation as well.
result_list = []
print("Welcome to Speed Cameras")
while 1:
result_list.append(input("New Reading: "))
if result_list == "END":
break
try:
max_speed = max(result_list)
min_speed = min(result_list)
avg_speed = len(result_list) / len(result_list)
print("Max is:", max, " MPH:")
print("Min is:", min, " MPH")
print("Avg is", avg_speed, "MPH")
finally:
print("Thanks For Submitting")
You have 2 issues and both are here
if result_list == "END":
break
result_list is a list so it will never be equal to a string, instead you could check if the last item is END like this result_list[-1] == "END"
the second problem you have is indentation, your break is not in the if statement but in the while loop, but this doesn't seem to be the case with your error, so i think you copied your code into the question with an error
Here is the code would work:
result_list = []
print("Welcome to Speed Cameras")
while 1:
# you need test the input first before append it to the list and not test the list
inp = input("New Reading: ")
if inp == "END":
break
else:
result_list.append(float(inp)) # turn your input into a number before appending
try:
max_speed = max(result_list)
min_speed = min(result_list)
# len(result_list) / len(result_list) make no sense, use sum()
avg_speed = sum(result_list) / len(result_list)
print("Max is:", max_speed, " MPH:") # your variable name was wrong here
print("Min is:", min_speed, " MPH") # your variable name was wrong here
print("Avg is", avg_speed, "MPH")
# since you try, you should do something when you don't pass the try
# 1 there is no input at all
# 2 the input need to be numbers
except:
print('at least one speed input is needed, or please make sure your input to be a number')
finally:
print("Thanks For Submitting")
A few mistakes:
Test the input instead of the list, and then append it to the list
Need to turn input into number
Average speed formula need to be fixed
Don't forget except in try-except-finally
Wrong variable names inside print()
Please reading your own code a few time before post it for help. Some mistakes like variable names and avg-speed formula, are easy to identify.
Anyway hope this would help.
I have written this code for an assignment and it not working as it should. I want my program to validate user input for 3 users when they enter the names and grades for 3 test. my program just check the first input and then asks for the other user name and skips asking the user for an input or validating the input.
validInput1 = False
validInput2 = False
validInput3 = False
studentnames = []
studentMarkTest1 = []
studentMarkTest2 = []
studentMarkTest3 = []
totalScores = []
sum = 0
for i in range(3):
sname = input("Enter Student name:")
while not validInput1:
score1 = int(input("What did {} get on their test 1?".format(sname)))
if score1 < 0 or score1 >20:
print("Invalid input")
else:
validInput1 = True
while not validInput2:
score2 = int(input("What did {} get on their test 2?".format(sname)))
if score2 < 0 or score2 >25:
print("Invalid input")
else:
validInput2 = True
while not validInput3:
score3 = int(input("What did {} get on their test 3?".format(sname)))
if score3 < 0 or score3 >35:
print("Invalid input")
else:
validInput3 = True
totalScore = score1+ score2+ score3
sum = sum + totalScore
AverageTestScore = sum / 3
# saving name and grade
studentnames.append(sname)
studentMarkTest1.append(score1)
studentMarkTest2.append(score2)
studentMarkTest3.append(score3)
totalScores.append(totalScore) for i in range(3):
print(studentnames[i],"total Test score",totalScores[i]) print("class average", AverageTestScore)
here what happens when i run the program
>>>
Enter Student name:g
What did g get on their test 1?44
Invalid input
What did g get on their test 1?33
Invalid input
What did g get on their test 1?44
Invalid input
What did g get on their test 1?22
Invalid input
What did g get on their test 1?20
What did g get on their test 2?34
Invalid input
What did g get on their test 2?23
What did g get on their test 3?55
Invalid input
What did g get on their test 3?44
Invalid input
What did g get on their test 3?32
Enter Student name:e
Enter Student name:e
g total Test score 75
e total Test score 75
e total Test score 75
class average 75.0
>>>
How can I get the highest test score value stored in totalscore and then print out the highest score with the name of the student with the highest score?
its easy to get confused when you have a big chunk of code like this ... instead try and split your problem into smaller parts
start with a function to get the details of only one student
def get_student_detail(num_tests): # get the detail for just 1 student!
student_name = input("Enter Student Name:")
scores = []
for i in range(1,num_tests+1):
scores.append(float(input("Enter Score on test %s:"%i)))
return {'name':student_name,'scores':scores,'avg':sum(scores)/float(num_tests)}
now just call this for each student
student_1 = get_student_detail(num_tests=3)
student_2 = get_student_detail(num_tests=3)
student_3 = get_student_detail(num_tests=3)
print("Student 1:",student_1)
print("Student 2:",student_2)
print("Student 3:",student_3)
or better yet implement a function that lets you keep going as long as you want
def get_students():
resp="a"
students = []
while resp[0].lower() != "n":
student = get_student_detail(num_tests=3)
students.append(student)
resp = input("Enter another students details?")
return student
you may want to split out get_student_details even further writing a method to get a single test score and validate that its actually a number (this will crash as is if you enter something that isnt a number as a test score), or to keep asking for test scores until an empty response is given, etc
def get_number(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
print ("That is not a valid number!")
def get_test_score(prompt):
while True:
score = get_number(prompt)
if 0 <= score <= 100:
return score
print("Please enter a value between 1 and 100!")
test_score = get_test_score("Enter test score for test 1:")
print(test_score)
Let's take a look at the while-loops you have:
while not validInput1:
The first time that your application runs, validInput1 is False, so this block evaluates. However, on subsequent loops (from for i in range(3):), validInput1 is already true, so this block is entirely skipped.
You can fix this by changing validInput1, validInput2 and validInput3 to False at the beginning of your for-loop.
That is because validInput1, validInput2 and validInput3 variables were set to True at first iteration but were not set to false for the second iteration.
Therefore for after first iteration your while conditions are always false due to "not True" i.e. False
Can set them to false again after each iteration i.e. at the end of the loop
You need to put validInput back to False after the while loops or even better replace them to the beginning of the for loop.
i made this code and i want it to tell me how many times it used to find the number i put in, and i want to tell how many times it should repite the action of finding the "stop_at"
print 'first write the random int (lowest number first)'
imp1 = float(raw_input())
imp2 = float(raw_input())
print 'the prosess will be between', imp1, 'and', imp2, 'when do you want to stop the opperation'
stop_at = float(raw_input())
while True:
num = random.randint(imp1, imp2)
if num == stop_at:
print
print
print stop_at, "were found after", ..., 'tryes'
print ' '
break
print num
You can add a counter
imp1 = int(raw_input("Enter low guess"))
imp2 = int(raw_input("Enter high guess"))
stop_at = int(raw_input("Enter the number you want guessed"))
i = 0
while True:
i += 1
num = random.randint(imp1, imp2)
if num == stop_at:
print "\n\n{0} was found after {1} tries\n\n".format(stop_at, i)
print num
First, You can't use float values as input parameters for random.randint function. Input parameters must be of type integer.
Second, same goes for stop_at. It must be integer, since random.randint will return integer (it MIGHT be float, but only if it is in form 2.0, 11.0...).
Third, You should introduce counter and increase it in if part of the code to get number of hits. Also, You should introduce counter which will be placed right inside while loop which will tell You how many loops were there.
Introduce some count variable that you will increment with each loop pass.
cnt = 0
while True:
num = random.randint(imp1, imp2)
cnt += 1
if num == stop_at:
print
print
print stop_at, "were found after tryes {}".format(cnt)
print
break
print num
trying to get a program to enter a students name and score, test it to make sure score is a vaule >=0 and <=100 and save results to a file and loop back
gradeFile = open("grade.dat","a")
Score = "0"
while Score>=0:
Name = raw_input("What is the students's name?: ")
Score = float(raw_input("What is the students's score?: "))
while Score <0 or Score >100 :
print("ERROR: the grade cannot be less than 0 or more than 100")
Score = float(raw_input("What is the students's score?: "))
gradeFile.write(Name+"\n")
gradeFile.write(Score+"\n")
gradeFile.close()
print("Data saved to grade.dat")
You need to have a way to exit the loop. For your outer loop, you automatically go in. Then you loop again until you get a valid score, via your inner loop, and you repeat. In your current configuration, there's no way to exit the loop.
Additionally, score should be a number, but you enter it as a string in Score = "0". When outputting, you're going to want to write str(Score) so that you can concatenate it with "\n".
I suggest that your outer loop have something like while Score >= 0 and userWantsToContinue. You can handle userWantsToContinue in whatever way you see fit.
Your datatpe doesn't match
Score = "0" # So, score is a string
while Score >= 0: # Oh, thenm it's a integer?