简体   繁体   English

如何在 Python 中创建无限输入?

[英]How do I create unlimited inputs in Python?

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.我应该编写一个程序来确定字母等级(A、B、C、D、F),跟踪有多少学生通过和失败,并显示 class 的平均值。 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."一个让我明白的部分是“该程序将能够处理用户在这个 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)

The infinite input can be done using the while loop .可以使用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)

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. EOFError - 如果您从文件中获取输入,您将收到此错误。

ValueError- In case wrong input is provided. ValueError -如果提供了错误的输入。

To ask for data an unlimited number of times, you want a while loop.要无限次请求数据,您需要一个 while 循环。

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.

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.看看并了解https://docs.python.org/3/library/itertools.html的想法,所以只为字母itertools.cycle('ABCDF') 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 .进一步阅读(对于概率分布)可能是https://numpy.org/doc/stable/reference/random/index.html

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.我试图以不同于使用 while True: 的方式来处理它,正如有人已经解释过的那样。 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 ).第一,更详细地参考了本示例中介绍的技术:( 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.随着您获得经验,您可能希望将此程序更改为输入除 integer 或浮点数以外的任何内容都会引发异常和/或不终止程序。 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.您甚至可以使用不同的结构(例如字典)来跟踪学生的姓名或 ID。 Basically, what I provided is just a working example around what I deemed students may already know at this point to get you started:)基本上,我提供的只是一个工作示例,围绕我认为学生此时可能已经知道的内容来帮助您入门:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM