For loop only executes 1 time, though given a range of 5(For 循环仅执行 1 次,但范围为 5)
问题描述
我有以下代码:
def input_scores():
scores = []
y = 1
for num in range(5):
score = int(input(print('Please enter your score for test %d: ' %y)))
while score < 0 or score > 100:
print ('Error --- all test scores must be between 0 and 100 points')
score = int(input('Please try again: '))
scores.append(score)
y += 1
return scores
当我运行它时,输出如下:
When I run it, the output is as follows:
Please enter your score for test 1:
None
然后我将在无旁边输入测试分数,例如 95然后它会运行程序的其余部分,而不提示我将下一个测试分数添加到分数列表中.我真的很好奇为什么会这样
Then I'll enter the test score next to None, as, say 95 It then runs through the rest of the program without prompting me for the next test score to add to the scores list. I'm really curious why that is
提前感谢您抽出宝贵时间提供帮助
Thanks in advance for taking the time to help
真诚地,~达斯汀
推荐答案
你的 return 语句缩进太多,导致函数在第一次迭代时返回.它需要在 for 块之外.此代码有效:
your return statement is indented too much, causing the function to return on the first iteration. It needs to be outside of the for block. This code works:
def input_scores():
scores = []
y = 1
for num in range(5):
score = int(input('Please enter your score for test %d: ' %y))
while score < 0 or score > 100:
print ('Error --- all test scores must be between 0 and 100 points')
score = int(input('Please try again: '))
scores.append(score)
y += 1
return scores
这篇关于For 循环仅执行 1 次,但范围为 5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:For 循环仅执行 1 次,但范围为 5
基础教程推荐
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 筛选NumPy数组 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01