[英]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.