r/learnpython • • Sep 15 '18

How do I do a loop for 10 times ?

0 Upvotes

12 comments sorted by

2

u/AlreadyTaken201 Sep 15 '18

for i in range(10): do_something()

1

u/mylesmerry Sep 15 '18

Thank you

1

u/blackmoon94 Sep 15 '18

python2.x: for _ in xrange(10): do_something()
python3.x: for _ in range(10): do_something()

0

u/mylesmerry Sep 15 '18

How do I repeat a chunk of code 10 times now.

2

u/AlreadyTaken201 Sep 15 '18

what do u wanna do exactly?

1

u/mylesmerry Sep 15 '18

Repeat

time.sleep(3) print.(‘Hello World’)

10 times

4

u/[deleted] Sep 15 '18
import time

for i in range(10):
    print('hello Dolly')
    time.sleep(3)

1

u/mylesmerry Sep 15 '18

It will also help with a turtle script

0

u/[deleted] Sep 15 '18

[deleted]

4

u/[deleted] Sep 15 '18

OP is obviously a beginner to the language if they can’t do a simple for loop. This is vastly over confusing for someone who’s new to Python.

for i in range(10):

Is all that was needed.

-1

u/[deleted] Sep 15 '18

Yes, on reflection, too much - I've deleted

(Although perhaps better to not use a single character variable name in defiance of PEP8 even in this small example maybe?)

1

u/JohnnyJordaan Sep 15 '18

Nope, i has been the default incrementor in programming languages since the earliest ones. Even the official Python tutorial uses it when it explains the range function here.

If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy. It generates arithmetic progressions:

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4

And also, you seem to have missed this part in PEP8

One of Guido's key insights is that code is read much more often than it is written. The guidelines provided here are intended to improve the readability of code and make it consistent across the wide spectrum of Python code. As PEP 20 says, "Readability counts".

A style guide is about consistency. Consistency with this style guide is important. Consistency within a project is more important. Consistency within one module or function is the most important.

However, know when to be inconsistent -- sometimes style guide recommendations just aren't applicable. When in doubt, use your best judgment. Look at other examples and decide what looks best. And don't hesitate to ask!

1

u/[deleted] Sep 15 '18

Cool, thanks very much.

I shall use i, j, etc more freely now (when appropriate) - I'd thought it a bad habit from decades ago that I had to drop, hence my asking.