CherryMX CherryMX -4 years ago 139
Python Question

Repeat an action a specified amount of times

Just for the record I'm just starting to use python, and I want to make it multiply a variable (let's call it

X
) by 2 and then the next time it comes back to this line to multiply it by 3 and so on till it's multiplied by 10.
I'll be adding some conditions before it goes back and multiplies
X
by the next number.
I think it's doable using the
FOR
loop, but the examples I found around the web weren't helpful, I started doubting if
FOR
is going to be helpful, that's why I'm here.

Answer Source

Actually, a for-loop is exactly what you want here:

>>> x = 1
>>> list(range(2, 11))
[2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> for i in range(2, 11):
...     x *= i
...     print(x)
...
2
6
24
120
720
5040
40320
362880
3628800
>>>

As you can see, this for-loop takes x (which starts at 1) and multiplies it by 2,3,4, etc. until it hits 10.

Regarding the conditions, you can add as many as you'd like inside the loop. See an example below:

>>> x = 1
>>> for i in range(2, 11):
...     if i != 3:    # I add a condition to skip 3
...         x *= i
...         print(x)
...
2
8
40
240
1680
13440
120960
1209600
>>>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download