我对编程很新,并且只做了一个月。目前我正在尝试获取用户输入,将其存储在列表中,并将该列表传递给函数。我在使用列表作为我的函数的参数(最后一行代码)时遇到了麻烦。提前谢谢!
grade_list = []
percentages = 0
while True:
percentages = input("Enter some numbers here: ")
if percentages == "done":
break
grade_list.append(percentages)
print(grade_list)
def gpaCalc(marks):
gpaList = []
for grade in marks: #sorts data
if grade <= 49.99:
grade = 0.00
elif 50 <= grade <= 52.99:
grade = 0.70
elif 53 <= grade <= 56.99:
grade = 1.00
elif 57 <= grade <= 59.99:
grade = 1.30
elif 60 <= grade <= 62.99:
grade = 1.70
elif 63 <= grade <= 66.99:
grade = 2.00
elif 67 <= grade <= 69.99:
grade = 2.30
elif 70 <= grade <= 72.99:
grade = 2.70
elif 73 <= grade <= 76.99:
grade = 3.00
elif 77 <= grade <= 79.99:
grade = 3.30
elif 80 <= grade <= 84.99:
grade = 3.70
elif 85 <= grade <= 89.99:
grade = 3.90
elif 90 <= grade <= 100:
grade = 4.00
gpaList.append(grade) #gathers data into list
gpaList.sort()
return gpaList
print (gpaCalc(PROBLEM))
答案 0 :(得分:1)
在最后一个print
行之前,定义您的商标列表,例如marks = [70, 68, 50, 89, ...]
并将其传递给函数调用中的gpaCalc:
print(gpaCalc(marks))
请注意,Python convention表示您不应在标识符中使用驼峰大小写;请改为使用下划线:gpa_calc
def get_user_input():
grades = []
while True:
# take input
value = ... # figure it out
if value == 'q':
break
try:
# do basic validation here
grades.append(int(value))
# might be a good idea to check the range too…
except ValueError:
print("This is not a valid grade!")
return grades
如果您想要解释,请发表评论!
答案 1 :(得分:1)
您可以传递一个列表,就像将它正常传递给任何函数一样,只需始终确保通过正确索引访问列表中的项目,而不是计算整个列表。请改用以下内容:
def gpaCalc(marks):
gpaList = []
for grade in marks[0]: #sorts data
if grade <= 49.99:
grade = 0.00
elif 50 <= grade <= 52.99:
grade = 0.70
elif 53 <= grade <= 56.99:
grade = 1.00
elif 57 <= grade <= 59.99:
grade = 1.30
elif 60 <= grade <= 62.99:
grade = 1.70
elif 63 <= grade <= 66.99:
grade = 2.00
elif 67 <= grade <= 69.99:
grade = 2.30
elif 70 <= grade <= 72.99:
grade = 2.70
elif 73 <= grade <= 76.99:
grade = 3.00
elif 77 <= grade <= 79.99:
grade = 3.30
elif 80 <= grade <= 84.99:
grade = 3.70
elif 85 <= grade <= 89.99:
grade = 3.90
elif 90 <= grade <= 100:
grade = 4.00
gpaList.append(grade) #gathers data into list
gpaList.sort()
return gpaList
grade_list = []
percentages = 0
while True:
percentages = input("Enter some numbers here: ")
if percentages == "done":
break
grade_list.append(percentages)
print(gpaCalc(grade_list))
答案 2 :(得分:1)
保持检查&#34;完成&#34;原样。如果没有完成,那么转换浮动。
while True:
percentages = input("Enter some numbers here and 'done' to exit:")
if percentages == "done":
break
try:
grade_list.append(float(percentages))
except ValueError:
pass
...排序
for grade in marks: #sorts data
.....
gpaList.append(grade) #gathers data into list
#also, sort outside the loop, when done, not each time.
gpaList.sort()
return gpaList