英文:
How python execute for loops in range()
问题
In this code, you are a beginner in Python and you want to understand how it works.
Here's a translation of the code explanation:
我是Python的初学者,我只想问一下这段代码是如何工作的:
for number in range(3):
print("attempt", number + 1, (number + 1) * ".")
在这行代码的第二个参数中,number的值应该变成1,对吗?
然后,如果我在下一个参数中再加上1并将点乘以它,第一个循环不应该得到2个点吗?这段代码到底发生了什么?(如果我的英语不好,我很抱歉)
Please let me know if you need any further assistance.
英文:
im a beginner in python and i just want ask how this code works:
for number in range(3):
print("attempt", number + 1, (number + 1) * ".")
in this line's second argument number's value should change to 1 right?
then if i am going to add another 1 in the next argument and multiply the dot, shouldnt i get 2 dots at first loop? what is really happening in this code? (sorry if my english is bad)
答案1
得分: 0
以下是翻译后的代码部分:
for number in range(3):
print("尝试", number + 1, (number + 1) * ".")
希望这对您有帮助。
英文:
for number in range(3):
print("attempt", number + 1, (number + 1) * ".")
range(3) means number gets values 0, 1 and 2
then inside print(), string "attempt" concatenated with number + 1 concatenated with string holding dot (".") multiplied by (number + 1)
the output will be
attempt 1 .
attempt 2 ..
attempt 3 ...
!! yes, you can multiply strings to numbers in python and it will repeat string number time
答案2
得分: 0
“range”函数返回不可变对象,您无法修改获取到的值。此外,即使您可以修改它们,您的代码也没有正确执行。如果您想增加名为“number”的变量的值,您应该使用number = number + 1
或number += 1
。
英文:
The function "range" returns immutable objects, you cannot modify the values you get. Also, even if you could modify them, your code does not do it properly. If you want to increase the value of a variable called "number" you should either do number = number + 1
or number += 1
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论