【问题标题】:How do I create unlimited inputs in Python?如何在 Python 中创建无限输入?
【发布时间】:2020-07-19 09:52:22
【问题描述】:

我应该编写一个程序来确定字母等级(A、B、C、D、F),跟踪有多少学生通过和不及格,并显示班级平均成绩。让我印象深刻的一个部分是“该程序将能够处理用户指示的班级中的尽可能多的学生。”如何创建无限的输入 - 用户想要的。

我基本上有一个关于我应该做什么的框架,但我一直坚持如何创建用户想要的尽可能多的输入,然后在其他功能上使用该信息(我如何获得所有这些信息。另一个函数)。

如果你们中的任何人能告诉我如何创建无限数量的输入,将不胜感激!!祝你们有美好的一天! :)

我的代码:

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)

【问题讨论】:

  • 您可以使用带有 True 条件的 while 循环。

标签: python function input


【解决方案1】:

可以使用while loop 完成无限输入。您可以将该输入保存到其他数据结构(例如列表)中,但您也可以在其下方放置代码。

while True:
    x = input('Enter something')
    determineGrade(x)
    determinePass(x)

【讨论】:

  • @JustinKim 你能点赞并接受我的回答吗?
  • 接受答案需要 10 分钟。再次感谢! :)
【解决方案2】:

要无限次请求数据,您需要一个 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.

【讨论】:

    【解决方案3】:

    试试这个。

    while True:
        try:
            variable = int(input("Enter your input"))
             # your code
    
        except (EOFError,ValueError):
            break
    

    EOFError-如果您从文件中获取输入,您将收到此错误。

    ValueError-万一输入错误。

    【讨论】:

    • 它将帮助您摆脱困境。 :)
    • @TheSohan 也许可以解释一下他如何召唤EOFError?你刚刚给他发了一个解释为 0 的代码
    • @AleksanderIkleiw EOFError 只是一个示例。如果提供了错误的输入数据,可能会出现值错误。添加了更多信息。
    【解决方案4】:

    查看并了解https://docs.python.org/3/library/itertools.html 的概念,因此itertools.cycle('ABCDF') 可能适合这些字母。或者对于分数:

    import random
    
    def next_input():
        return random.randint(1, 100)
    
    if __name__ == '__main__':
        while True:
            studentScore = next_input()
            print(f"score: {studentScore:3}")
    

    进一步阅读(概率分布)可能是https://numpy.org/doc/stable/reference/random/index.html

    【讨论】:

    • 这看起来很有趣。我会确保我调查它。非常感谢!! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-13
    • 2017-09-29
    • 2013-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多