Python 3.x 循环函数建议
我目前正在学习一门关于python基础知识的课程,我有一个关于以下循环函数的问题:Python 3.x 循环函数建议,python-3.x,Python 3.x,我目前正在学习一门关于python基础知识的课程,我有一个关于以下循环函数的问题: x = 0 for index in range(5, 10): x = x + 10 print("The value of X is {}".format(x)) 当我打印它时,我得到以下结果: The value of X is 10 The value of X is 20 The value of X is 30 The value of X is 40 The value of X
x = 0
for index in range(5, 10):
x = x + 10
print("The value of X is {}".format(x))
当我打印它时,我得到以下结果:
The value of X is 10
The value of X is 20
The value of X is 30
The value of X is 40
The value of X is 50
这就是我感到困惑的地方,我期待着这样的结果:
The value of X is 60
The value of X is 70
The value of X is 80
The value of X is 90
The value of X is 100
我误解了什么吗?将
x
的初始值设置为0
,在循环的每次迭代中,您都要向其添加10。这就是为什么会得到这些值。函数有效地做的是调用
x = x + 10
五次。因为它是用x=0
初始化的,所以输出对我来说是有意义的
循环中的索引
变量根本不使用。以下循环是等效的:
for _ in range(5, 10):
...
for i in range(0, 5):
...
在您的情况下,只需重复某个操作5次即可
如果希望获得问题中所述的输出,则需要按如下方式修改循环:
x = 10
for i in range(5, 10):
# This loop will be performed for values
# of i of [5, 6, 7, 8, 9], so it includes
# the first value (5) and excludes that last
# one (10)
print(x * i)
>> 50
>> 60
>> 70
>> 80
>> 90
逐行查看代码:
- 首先,将变量x初始化为值0李>
- 然后设置一个循环,该循环将运行五次
- 将x的原始值加10,然后将该新值设置为x
- 打印x的值
- 重复5次
>>> x = 0
>>> for index in range(6, 11):
... x = index * 10
... print("The value of X is {}".format(x))
The value of X is 60
The value of X is 70
The value of X is 80
The value of X is 90
The value of X is 100
这里是x的值,每个循环迭代的索引
Iteration 1. x = 10 + 0 , index = 5
Iteration 2. x = 10 + 10 , index = 6
Iteration 3. x = 10 + 20 , index = 7
Iteration 4. x = 10 + 30 , index = 8
Iteration 5. x = 10 + 40 , index = 9
这就是循环执行的方式我相信您希望它是这样的
x = 0
for index in range(6,11):
x = index*10
print("The value of X is {}".format(x))
x从0开始,然后
x=x+10(10=0+10),现在x=10,然后
x=x+10(20=10+10),现在x=20
你为什么期望60-100?没有乘法,
index
在任何计算中都没有使用。你甚至没有使用index
,这正常吗?我知道index没有任何价值,我现在正在学习Python基础知识,index只是一个占位符。感谢Daniel,在这个范围内,我将start int设置为5,stop设置为10。因此,如果我理解正确,它不应该从50打印开始,直到达到100。循环只更新索引的值,而您根本不用它。因此,它的范围是从0到5,从5到10,还是从1019到1024并不重要。这只是关于在循环中执行代码五次,将x的值从0增加到10到20到30,等等。谢谢你总结了它。谢谢Ethan,但正如我在范围内对Daniel所说的,我将开始int设置为5,停止int设置为10。因此,操作不应该从50开始计数并在达到100时停止吗?范围(5,10)
将生成如下数组:[5,6,7,8,9]
该数组中有5个数字,因此循环将运行多少次。for循环对每个数组元素在数组上迭代一次。这些数字与x的值无关。非常感谢。。。这就是我感到困惑的地方。现在我明白了,我希望它从50开始,到100。谢谢你的回复。谢谢你的回复