簡體   English   中英

如何在 Python 中創建無限輸入?

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

我應該編寫一個程序來確定字母等級(A、B、C、D、F),跟蹤有多少學生通過和失敗,並顯示 class 的平均值。 一個讓我明白的部分是“該程序將能夠處理用戶在這個 class 中指示的盡可能多的學生。” 如何創建無限制的輸入 - 盡可能多地滿足用戶的需求。

我基本上有一個關於我應該做什么的框架,但我堅持如何創建用戶想要的盡可能多的輸入,然后在其他功能上使用該信息(我如何將所有這些信息。到另一個功能中) .

如果你們中的任何人可以告訴我如何創建無限數量的輸入,將不勝感激:! 祝你們有美好的一天! :)

我的代碼:

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)

可以使用while loop來完成無限輸入。 您可以將該輸入保存到其他數據結構(例如列表)中,但您也可以在其下方放置代碼。

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

試試這個。

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

    except (EOFError,ValueError):
        break

EOFError - 如果您從文件中獲取輸入,您將收到此錯誤。

ValueError -如果提供了錯誤的輸入。

要無限次請求數據,您需要一個 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.

看看並了解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

我將提供另一個示例,以防這是一項可能讓其他人感到困惑的作業。 我試圖以不同於使用 while True: 的方式來處理它,正如有人已經解釋過的那樣。 我將使用標記值或導致循環終止的值。 見下文:

"""
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: "))

我想補充一些重要的注意事項。 第一,更詳細地參考了本示例中介紹的技術:( https://redirect.cs.umbc.edu/courses/201/fall16/labs/lab05/lab05_preLab.shtml )。

其次,我嘗試根據您的代碼和解釋中提供的功能要求遵循我的格式,但由於我沒有指南,您可能需要重新格式化一些東西。

第三,我嘗試使用您或某人可能在不久的將來學習或已經學習到此任務的技術。 隨着您獲得經驗,您可能希望將此程序更改為輸入除 integer 或浮點數以外的任何內容都會引發異常和/或不終止程序。 您可能還希望通過移動或修改某些內容來降低運行時的復雜性。 您甚至可以使用不同的結構(例如字典)來跟蹤學生的姓名或 ID。 基本上,我提供的只是一個工作示例,圍繞我認為學生此時可能已經知道的內容來幫助您入門:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM