Python如何执行范围内的for循环。

huangapple go评论71阅读模式
英文:

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) * ".")

Python如何执行范围内的for循环。

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 + 1number += 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

huangapple
  • 本文由 发表于 2023年7月18日 12:45:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76709595.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定