How do I create unlimited inputs in Python?

Question:

I’m supposed to write a program that will determine letter grades (A, B, C, D, F), track how many students are passing and failing, and display the class average. One part that is getting me is that "the program will be able to handle as many students as the user indicates are in this class." How to I get to create unlimited inputs – as much as the user wants.

I basically have a framework upon what I should do, but I’m stuck on how I could create as many inputs as the user wants and then use that information on the other functions (how I could get all those info. into another function).

If any of you guys can tell me how to create unlimited number of inputs, it would be greatly appreciated!! Have a great day guys! 🙂

My code:

studentScore = input("Grade for a student: ")

fail = 0
def determineGrade (studentScore):
    if studentScore <= 40:
        print 'F'
    elif studentScore <= 50:
        print 'D'
    elif studentScore <= 60:
        print 'C'
    elif studentScore <= 70:
        print 'B'
    elif studentScore <= 100:
        print 'A'
    else:
        print 'Invalid'

def determinePass (studentScore):
    for i in range():
        if studentScore <= 40:
            fail += 1
        else:
            Pass += 1

def classAverage (studentScore):
    

determineGrade(studentScore)
determinePass(studentScore)
Asked By: Justin Kim

||

Answers:

The infinite input can be done using the while loop. You can save that input to the other data structure such a list, but you can also put below it the code.

while True:
    x = input('Enter something')
    determineGrade(x)
    determinePass(x)
Answered By: Aleksander Ikleiw

Try this out.

while True:
    try:
        variable = int(input("Enter your input"))
         # your code

    except (EOFError,ValueError):
        break

EOFError- You will get this error if you are taking input from a file.

ValueError- In case wrong input is provided.

Answered By: TheSohan

To ask for data an unlimited number of times, you want a while loop.

scores=[]    
while True:
    score=input("Students score >>")
    #asks for an input
    if score in ("","q","quit","e","end","exit"):
        #if the input was any of these strings, stop asking for input.
        break
    elif score.isdigit():
        #if the input was a number, add it to the list.
        scores.append(int(score))
    else:
        #the user typed in nonsense, probably a typo, ask them to try again 
        print("invalid score, please try again or press enter to end list")
#you now have an array scores to process as you see fit.
Answered By: Donald Hobson

Have a look into and get the idea of https://docs.python.org/3/library/itertools.html, so just for the letters itertools.cycle('ABCDF') might fit. Or for the scores:

import random

def next_input():
    return random.randint(1, 100)

if __name__ == '__main__':
    while True:
        studentScore = next_input()
        print(f"score: {studentScore:3}")

Further read (for probability distributions) could be https://numpy.org/doc/stable/reference/random/index.html.

Answered By: thoku

I will provide another example in case this is an assignment that may have others confused. I tried to approach it differently than using while True: as someone already explained this. I will be using a sentinel value(s) or the value(s) that cause a loop to terminate. See below:

"""
I kept your function the same besides removing the invalid conditional branch and adding a 
print statement
"""
def determineGrade (studentScore):
    print("Student earned the following grade: ", end = " ")
    
    if studentScore <= 40:
        print ('F')
    elif studentScore <= 50:
        print ('D')
    elif studentScore <= 60:
        print ('C')
    elif studentScore <= 70:
        print ('B')
    elif studentScore <= 100:
        print ('A')

"""
I kept this function very similar as well except I used a list initialized in main so you have a 
history of all student scores input and how many passed or failed. I also put the fail and passing
variables here for readability and to avoid scope problems.
"""
def determinePass (score_list):
    fail = 0
    passing = 0
    
    for i in range(len(score_list)):
        if score_list[i] <= 40:
            fail += 1
        else:
            passing += 1
            
    print("Students passing: {}".format(passing))
    print("Students failing: {}".format(fail))

"""
I finished this function by using basic list functions that calculate the average. In the future,
use the keyword pass or a stub in your definition if not finished so you can still test it :)
"""
def classAverage (score_list):
    avg = sum(score_list) / len(score_list)
    
    print("Class Average: {}".format(avg))

""" MAIN """
if  __name__ == "__main__":
    # Makes sentinel value known to the user (any negative number).
    print("Welcome. Input a negative integer at any time to exit.")
    # Wrapped input in float() so input only accepts whole and decimal point numbers. 
    studentScore = float(input("Grade for a student: "))
    # Declares an empty list. Remember that they are mutable meaning they can change even in functions.
    score_list = []
    
    # Anything below 0 is considered a sentinel value or what terminates the loop. 
    while studentScore >= 0:
        # If input score is between 0-100:
        if studentScore <= 100:
            # Input score is added to our list for use in the functions.
            score_list.append(studentScore)
            
            determineGrade(studentScore)
            determinePass(score_list)
            classAverage(score_list)
        # If a number beyond 100 is input as a score.
        else:
            print("Invalid. Score must be between 0-100")
        
        # Used to avoid infinite loop and allow as many valid inputs as desired.
        print("Welcome. Input a negative integer at any time to exit.")
        studentScore = float(input("Grade for a student: "))

Some important notes I would like to add. One, a reference to what techniques were introduced in this example with a little more detail: (https://redirect.cs.umbc.edu/courses/201/fall16/labs/lab05/lab05_preLab.shtml).

Second, I tried to follow my formatting based on the functional requirements provided in your code and explanation, but since I did not have the guidelines, you may need to reformat some things.

Third, I tried to use techniques that you or someone is likely learning in the near future or already learned up to this assignment. As you gain experience, you may wish to alter this program to where entering anything but an integer or float will throw an exception and/or not terminate the program. You may also wish to reduce the runtime complexity by shifting or modifying some things. You could even track the name or id of students using a different structure such as a dictionary. Basically, what I provided is just a working example around what I deemed students may already know at this point to get you started 🙂

Answered By: John B.
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.