I have a question about input loops and keeping track of it.
I need to make a program that will keep track of all the grades of a class. The thing is that the class size varies every semester, so there is no fixed number assigned to the number of students.
The program will stop taking input when a student enters a grade of -1.
while True:
grade = int(input("Test: "))
if grade < 0:
break
How can I make it so that it keeps track of every single input?
You could use a list comp with iter and get the user to enter -1 to end the loop:
grades = [int(grade) for grade in iter(lambda:input("Enter grade or -1 to exit: "), "-1")]
iter takes a sentinel that will break the loop when entered, so as soon as the user enters -1 the loop will end.
When taking input and casting you should really use a try/except to validate what the users inputs:
grades = []
while True:
try:
grade = int(input(""Enter grade or -1 to exit: ""))
except ValueError:
# user entered bad input
# so print message and ask again
print("Not a valid grade")
continue
if grade == -1:
break
grades.append(grade) # input was valid and not -1 so append it
grades = [] # initialize an empty list
while True:
grade = int(input("Test: "))
if grade < 0:
break
else:
grades.append(grade) # add valid values to the list
Related
number = 0
number_list = []
while number != -1:
number = int(input('Enter a number'))
number_list.append(number)
else:
print(sum(number_list)/ len(number_list))
EDIT: Have found a simpler way to get the average of the list but if for example I enter '2' '3' '4' my program calculates the average to be 2 not 3. Unsure of where it's going wrong! Sorry for the confusion
Trying out your code, I did a bit of simplification and also utilized an if statement to break out of the while loop in order to give a timely average. Following is the snippet of code for your evaluation.
number_list = []
def average(mylist):
return sum(mylist)/len(mylist)
while True:
number = int(input('Enter a number: '))
if number == -1:
break
number_list.append(number)
print(average(number_list));
Some points to note.
Instead of associating the else statement with the while loop, I revised the while loop utilizing the Boolean constant "True" and then tested for the value of "-1" in order to break out of the loop.
In the average function, I renamed the list variable to "mylist" so as to not confuse anyone who might analyze the code as list is a word that has significance in Python.
Finally, the return of the average was added to the end of the function. If a return statement is not included in a function, a value of "None" will be returned by a function, which is most likely why you received the error.
Following was a test run from the terminal.
#Dev:~/Python_Programs/Average$ python3 Average.py
Enter a number: 10
Enter a number: 22
Enter a number: 40
Enter a number: -1
24.0
Give that a try and see if it meets the spirit of your project.
converts the resulting list to Type: None
No, it doesn't. You get a ValueError with int() when it cannot parse what is passed.
You can try-except that. And you can just use while True.
Also, your average function doesn't output anything, but if it did, you need to call it with a parameter, not only print the function object...
ex.
from statistics import fmean
def average(data):
return fmean(data)
number_list = []
while True:
x = input('Enter a number')
try:
val = int(x)
if val == -1:
break
number_list.append(val)
except:
break
print(average(number_list))
edit
my program calculates the average to be 2 not 3
Your calculation includes the -1 appended to the list , so you are running 8 / 4 == 2
You don't need to save all the numbers themselves, just save the sum and count.
You should check if the input is a number before trying to convert it to int
total_sum = 0
count = 0
while True:
number = input("Enter a number: ")
if number == '-1':
break
elif not number.isnumeric() and not (number[0] == "-" and number[1:].isnumeric()):
print("Please enter numbers only")
continue
total_sum += int(number)
count += 1
print(total_sum / count)
I've been trying to work with this while loop so I ask for the user input, specifically a number between 99 and 1000. I've been trying to make it so that if your input is within those perimeters, it continues, and if it's not within those perimeters, the input question repeats until it receives a valid input.
while True:
try: #lttr = level two top range
lttr = int(input('Enter a triple digit number between 100 and 1000: '))
if lttr in range(99,1000):
continue
if lttr not in range(99,1000):
break
except:
print("That's not a valid option!")
we have been tasked with writing a program in python asking a user to enter multiple numbers.
the subject is while loops,so we can only make use of while loops and if statements.
when the user wants to stop the entry of numbers,the user then needs to type '-1'.
once that has been done,the program must return the average of the numbers entered by the user.
this is what i have so far:
#task 13-while.py
#first the program will explain to the user that the user can keep
#entering numbers until -1 occurs.
num = int(input('''please enter any number of your choice\n
please enter -1 to stop entry and run program'''))
num_count = 0
while num > -1:
num_count = num_count + 1
average = sum(num)/num_count
if num == -1:
print("the average of the numbers you have entered is"+ average)
extremely inexperienced with python,all help will be greatly appreciated.
You need to put the input into the while and then only when the loop is over calculate the averageLike this:
num = int(input("enter numbers and then -1 to stop: "))
num_count = 1
sum = num
while num!=-1:
num = int(input("another number: "))
num_count+=1
sum+=num
print(sum/num_count)
In order for it to work you need to add an input() call inside the while loop like in the code bellow :
count = 0
sum = 0
num = int(input('''please enter any number of your choice\n
please enter -1 to stop entry and run program\n'''))
while num != -1:
sum += num
count +=1
num = int(input('''Give another integer\n'''))
print("the average of the numbers you have entered is", sum/count)
Personal advice : I would suggest for you to read more tutorials or ask your peofessor for more work
I'm doing a project whereby a user has to input the value. The loop should end if the user key in the value of more than 300 for 3 times. If the user key in a value lesser than 300, a warning message should be prompted. And another criteria is that I need to allow the user to get out of the loop if the user do not meet the condition above. For now, I tried to do by using the list but my code doesn't seem to count the number of inputs.
list1 = list()
counter = 1
while counter <= 3:
ask = float(input("Please enter each of the value: "))
while ask != "":
list1.append(str(ask))
ask = float(input("Please enter each of the value: "))
if ask >= 50:
counter += 1
else:
print("Value must be more than 300. If you do not meet the criteria, please press 'enter'. ")
print(list1)
The following code is my original code which doesn't take into account of the minimum input value.
counter = 1
while counter <= 3:
ask = float(input("Please enter each of the value: "))
if ask >= 50:
counter += 1
else:
print("Value must be more than 300 ")
I would appreciate if anyone of you can help me out.
The problem is your inner while loop can't exit since ' "" ' (your exit signal) cannot be converted to float. Instead it will raise a ValueError.
One possible solution to this would be to try converting input to float and except the ValueError. It could look something like this.
list1 = list()
counter = 1
while counter <= 3:
try:
ask = float(input("Please enter each of the value: "))
except ValueError:
break
list1.append(str(ask))
if ask >= 50:
counter += 1
else:
print("Value must be more than 300. If you do not meet the criteria, please press 'enter'. ")
print(list1)
I think the program doesn't work as you want because you made two while loops:
the first while's condition is while counter<=3, ok but then you made another while which condition is ask !="", so the program will run inside this second while loop until the condition is no more true and the first while does not "see" the counter's changes.
By the way, I think you can simply use only one while loop(the first one), and write an if condition that verify the value(>300).
When you try to cast a string element into a float type it will throw an error if the value could not be casted to that type, you could use a try-except block.
while counter < 3:
try:
ask = float(input("xxxxx")
if ask >= 50:
counter += 1
else:
print("xxxxx")
except ValueError:
break
print(list1)
I am trying to create a simple program that initializes a list for the grades to be entered by the user and adds grades to the grade list. Also I want my user to be able to repeatedly prompt grades to the list until the user enters a blank grade. My problem is my code does not stop when a blank input is placed by the user.
Here is my initial code:
grade_list=[]
valid_input=True
while valid_input:
grade= input ("Enter your grade:")
grade_list.append(grade)
else:
valid_input= false
print(grade_list)
grade_list = []
while True:
grade = input('Enter your grade: ')
if not grade:
break
grade_list.append(grade)
print(grade_list)
Two problems:
(1) You never change the value of valid_input: you cannot get to the "else" branch.
(2) You don't do anything in the "true" branch to check the input.
You can get rid of the variable and simplify the loop: just grab the first input before the loop, and then control the loop by directly checking the input. This is the "old-school" way to run a top-checking loop.
grade_list = []
grade = input ("Enter your grade:")
while grade:
grade = input ("Enter your grade:")
grade_list.append(grade)