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)
Related
I really don't know what I am doing wrong here but whenever I run the code the output doesn't calculate the variable and only sets it to 0.0
total = 0.0
num1 = 0.0
average = 0.0
while True:
input_num = input("Enter a number ")
if input_num == 'done':
break
try:
num = float(input_num)
except ValueError:
print("Invalid Input")
continue
total = total + num
num1 = num1 + 1
average = total / num1
print("total: ", total)
print("count: ", num1)
print("average: ", average)
I got the following after running the code
[Image of code run]: (https://imgur.com/a/lEz6ibh)
Your code isn't indented properly, so the code after continue never gets executed. To get it to work, unindent the lines after continue:
total = 0.0
num1 = 0.0
average = 0.0
while True:
input_num = input("Enter a number ")
if input_num == 'done':
break
try:
num = float(input_num)
except ValueError:
print("Invalid Input")
continue
total = total + num
num1 = num1 + 1
average = total / num1
print("total: ", total)
print("count: ", num1)
print("average: ", average)
This should work.
num_list = []
while True:
input_num = input("Enter a number ")
if input_num == 'done':
total = sum(num_list)
average = total / len(num_list)
break
num_list.append(float(input_num))
print(f"Average: {average}")
print(f"Total: {total}")
print(f"num_list: {num_list}")
total = 0.0
num1 = 0.0
average = 0.0
while True:
input_num = input("Enter a number ")
if input_num == 'done':
break
try:
num = float(input_num)
total = total + num
num1 = num1 + 1
average = total / num1
except ValueError:
print("Invalid Input")
continue
print("total: ", total)
print("count: ", num1)
print("average: ", average)
Your code to calculate values should be inside the try block rather than the except block otherwise they are never executed.
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)
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)
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.
python 2.7: Count how many numbers are entered by the user.
I can't figure out how to count the raw_input... here's what I have so far:
while True:
datum = raw_input('enter a number: ')
if datum == 'done': break
count = 0
for line in datum:
if datum == int(datum):
count = count + 1
print 'count', count
You can use try and except
count=0 should be before the while
try:
count = 0
while True:
datum = raw_input('enter a number: ')
if datum == 'done': break
try:
int(datum)
count += 1
except ValueError:
pass
print 'count', count
datum = []
total = 0
count = 0
while True:
data = raw_input('enter a number: ')
if data == 'done': break
datum.append(data)
for i in datum:
try:
total = total + int(i)
count += 1
except:
pass
print 'count', count, ' total',total
count = 0
while True:
dat_num = raw_input('enter a number: ')
if dat_num == 'done':break
else:
dat_num = int(dat_num)
count += dat_num
print 'count', count