Python Loop X Times


Learning loops is crucial to expertise why anyone would certainly ever before want to go through the hassle of finding out programming in the first place. When you deserve to write a loop, you deserve to turn immaybe tedious tasks (i.e. work-related that is thneed to be “impossible” bereason no human could ever before sit through it) right into trivial job-related for a computer system.

You watching: Python loop x times

Although tright here are several kinds of loops, we emphasis on the a lot of common variation in Python: the for-loop.

Note: I arrangement to expand also this area a tiny little, yet you might additionally simply review the great leskid here: Chapter 2: Flow Control – for Loops and the range() Function

Why loop?

A loop is a programming construct in which we define a block of code that we desire the computer system to execute repeatedly, and also how many times the computer system must execute that block of code.

By "block of code", I intend, any code. For instance, here"s the Python code to print "hello world":

print("hello world")And here"s the script that repeats that "block of code" 5 times:

print("hello world")print("hello world")print("hello world")print("hello world")print("hello world")That"s straightforward enough. But what if I wanted to run that block of code 50 times. Or 5,000,000 times? Copy-and-paste have the right to only obtain us so much.

But through a loop, we deserve to command also the computer system to execute that block of code as many kind of times as we want, without physically composing that code, over and also over.

Here"s what the previous print-hello-world-5-times manuscript looks choose, as an easy for-loop in Python:

for x in range(5): print("hello world")Anatomy of a really boring for-loopBelieve it or not, there"s a lot to understand in that boring two-line snippet. Here are the highlights, which I"ll sophisticated on throughout this leschild.

That range() attribute takes creates one of Python"s data types. It"s harder to accurately and also totally define than it is to simply intuit: the range() feature takes one dispute and produces a sequence of numbers from 0 up till that dispute. The range() function itself is not a fundamental component of the _for-loop – I just usage it in _this standard instance as it"s the easiest means in Python to say: hey, iteprice 5 times. However, what the range() represents – a boundary problem – is fundamental to the for-loop: it states the variety of times the loop must execute. The keyword for is one of Python"s few special keywords, i.e. you can not name a variable for, and in a text-editor, it have to be highlighted. The keyword in is additionally an additional one-of-a-kind booked keyword. That x is not a keyword. It"s a variable name. And one that is superfluous since it"s not actually provided as anything ideal currently yet a placeholder. That colon at the end of the for statement is required. It basically tells the Python interpreter: everything after this line is the block of code to be executed The block of code to be executed, e.g. that print() statement, is indented 4 spaces. This is a requirement by Python, not simply an aesthetic thing.

Execute a boring for-loop in interactive Python

Before we acquire bogged down in the details, form out and execute the over code in the interenergetic Pythong interpreter (i.e. ipython). A few nuances will come up even in the execution of those two lines.

Note: if you are utilizing ipython – which you should be doing – as shortly as you hit Enter to go to the next line, the interpreter will certainly immediately add an indentation for you. If you are utilizing the consistent python__interpreter, you will certainly need to execute this manually, either by hitting __Tab as soon as, or the Spacebar 4 times.

Another note: When you type in the print("hello world") line and then hit Enternothing will happen. That is, the Python interpreter will certainly prompt you for another line of code to execute as a block rather of printing out, "hello world". Just hit Enter an additional time.

Here"s what the code looks choose once you kind it out in ipython – note just how ellipses are offered to show the continuation of the code block inside the for-loop:


Variations on a very boring for-loop

So that"s a really boring for-loop. Luckily, the building and construction of a for-loop doesn"t get even more complex than what I"ve outlined over. However, it is critical that you understand the standard elements of a for-loop before moving on – i.e. the use of the keywords for and also in, the colon at the end of the statement, and exactly how the block of code to be executed is indented.

Before relocating on, attempt these variations:

Relocation x through whatever_variable_name_I_feel_choose (or some other equally obnoxious yet valid variable name) to confirm that the literal x character is of no prestige. Relocation the 5 inside the range() function with 5000 or also 5000000. Don"t issue, this shouldn"t break your computer. Though it might take a couple of minutes to complete. Hit Ctrl-C to break execution if you obtain bored. Add a second line – e.g. print("goodbye world") in the indented block of code.Anatomy of a slightly much less boring for-loop

Loops gain a bit even more amazing when you have the right to create a task that varies upon each iteration. Remember that unsupplied x variable in the initially boring example? Let"s encompass it in the print() statement to check out what it contains:

for x in range(0, 5): print("hello world", x)The output:

hello world 0hello civilization 1hello civilization 2hello human being 3hello civilization 4 Instead of printing simply the very same "hello world", over and over, we"ve controlled to tell the computer to print something different through each iteration. Note that we haven"t enhanced the complexity of the for statement at all. Though, to be hoswarm, we haven"t raised the complexity of the program"s real civilization worth by a lot either.

But let"s have a brief segue and imagine exactly how also simply incrementing by one can be incredibly useful in the actual people. What if there were a collection of documents or webpages that all were associated or incredibly comparable, except for a solitary digit in the URL?

For instance, Wikipedia has pperiods for a lot of points, including numerals. Here"s the page for the number 1. Actually, it"s the web page for the year 1 A.D. – if you desire the number 1, you desire this URL:

OK, what if we wanted to print the URLs for the Wikipedia pages for the initially 10 years (A.D.), beginning via year 1 A.D.? The code and its output would certainly look like this, if you attempt it at the interenergetic Python shell:

(note that the range() function can take a second dispute, which creates a sequence of numbers from the first to the second argument)

(also note that we have to transform the number stood for by the yr variable right into a string literal in order to "add" it to the base URL)

Well, you can specify that indented block of code to do whatever you want:

base_url = ""for x in range(1, 11): url = base_url + str(x) print(url) foo_bar_dosomethin(url)Thinking and programming non-livirtually via loopsAssuming you"re reading this leskid prior to you"ve check out the leskid on conditional branching, the for-loop statement will be the initially time that you"ve explicitly composed code that did not execute in the top-to-bottom order in which you created it.

Consider this example:

for z in range(3): print("hello world")print("I"m done saying hello")When I intend that the code executes non-linearly, I suppose that also though this is the 3rd (and final) line of the script:

print("I"m done saying hello")– it"s not the 3rd command to be executed. Instead, the 2nd line, the indented code block –

print("hello world")– has to run its course. This is a much various paradigm than writing a script in which one line is executed after another.

In fact, to gain the complete result of this leschild, implement the above snippet in 2 various ways:

1. Type it out in your interenergetic Python shell

Aobtain, note how the indented code does not execute till you"ve hit Enter twice, consecutively, to signify the finish of the indented code block.


2. Type it out and save as a standalone script

Now open up your message editor, compose the code in a message file and conserve it. Then execute that file via the command-line Python interpreter:

$ python mytestmanuscript.pyhello worldhello worldhello worldI"m done saying hello

How to interproactively test a for-loop

One takeamethod is that it have the right to be a massive pain to write and execute even a basic for-loop inside the interenergetic Python shell, because the shell sort of stops being interactive once you indent a block, i.e. hitting Enter does not rerevolve a solution.

See more: Customer Reviews: Musashi Book Review, Musashi By Eiji Yoshikawa

So as you compose even more loops and also other constructs that call for indented blocks of code, I recommfinish that you just carry out it in the text editor via Python syntax highlighting, then paste it into the shell.

In truth, if you"re using ipython (which, aobtain, you should be making use of as your interenergetic shell), you have the right to form in the distinct command also %paste – which will paste in whatever is currently copied to your clipboard.

However before, the proper method to test out a loop is to just run one iteration, and assign a worth to the placeholder variable. Pretend that this is your finish script:

for xval in range(100): url_part_a = "" url_part_b = "_(number)" full_url = url_part_a + str(xval) + url_part_b print("Downloading", full_url)To test it interactively, simply assign xval as a normal variable. Then type out the remainder of the indented block as if it existed as a standalone script, without that for-loop construct:

Due to the fact that if it works for 42, or for any type of number between 1 and 100 – then you deserve to be reasonably assured that it will certainly job-related for all those other numbers.

Sequences and various other iterable objects

To store things straightforward, I"ve provided the range() function/object as the thing to be looped through, i.e. the sequence, i.e. the iterable.

Tbelow are many other sequences and iterable-kind objects that deserve to be supplied in a for-loop. I"ll list the prevalent ones below, yet it is by no suggests an exhaustive list. For the a lot of component, you learn what is iterable/loopable via experience:

Characters in a string

When a string literal is passed into the for statement, the code block will be executed for each character:

A list or tuple

The list object is most likely the most constant iterable object you"ll come across in Python:

numbers = <4, 5, 6>for x in numbers: print(x)Tuples (which are basically simplified lists) occupational in a similar fashion:

numbers = (6, 7, 8)for x in numbers: print(x)

Reading a file, line by line

A file object in Python is a particular kind of iterable object, in which a stream of information is stood for. When this is passed into the for-loop construct, the loop executes for every line in the file.

Pretfinish you have actually a file on your difficult drive called example.txt, and its contents look favor this:

hello worldandgoodbyeTo open up it, then loop with it line-by-line (with the code block ssuggest printing out an upper-case variation of each line):

Variations on loops

Understanding the for-loop construct is sufficient, as it is by far the a lot of prevalent kind of loop you will check out in Python. However, it"s worth pointing out the other variations and scenarios that you can watch in the wild.

While loops

Just like for, the keyword while is reserved in Python. And similarly, while is likewise provided to represent a block of code to be looped:

x = 0while x 3: print("hello world", x) x += 1 With the for-loop, you specify a arsenal of items to be iterated throughout. With a while-loop, you specify a condition that, if True, indicates that the code block need to be executed. In the over snippet, the variable x is incremented with each iteration of the loop. When x represents the worth 3, the problem becomes False, and also the loop stops.

Think around what the indistinguishable for-loop would certainly look choose, then try to create it down. Here"s my answer (note that there are literally infinite variety of means to reexisting this loop, bereason math and also etc.):

for z in range(0, 3): print("hello world", z)

Infinite loops

What if a condition is always True? Then, that loop will run forever, theoretically, as long as the legislations of logic do not adjust. Practically speaking, of course, it will probably end when your computer system runs out of power or the cosmos reaches heat-death.

Here"s an instance of an limitless while loop:

while 2 > 1: print("hello world")Or to be more succinct:

while True: print("hello world")And occasionally, you could accidentally write a loop that you don"t realize will be infinite:

x = 0while x 3: print("hello world", x) x + 1Because the value stood for by x never before alters (i.e. x is never before reassigned the result of x + 1), the value of x is forever before at 0, i.e. much less than 3.

Non-looping loops

What if a while loop condition is always False? Then the code inside the loop will certainly never run:

while 2 1: print("hello world")while False: print("hello world")It"s pretty easy to develop a for-loop variation of the non-executing loop:

for x in range(0): print("hello world")for x in < >: print("hello world")While tbelow are real-civilization reasons to have actually infinitely-running loops – generally you do not intfinish to create a loop that never actually loops.

Loops within loops

A code block within a loop is simply like any other code you can create. It can be multi-line, for example. Or it can include other code blocks, including another sepaprice loop:

for x in range(10): for y in range(5): for z in range(3): print(x, y, z)Can you guess just how many type of lines of output the over manuscript (which is as pointless as it seems)? Don"t issue, in real-world scripts, loops-within-loops will usually make more sense, e.g. it will not involve simply going via a range of arbitrary numbers. However, loops-inside-of-loops can get confmaking use of very easily. If your routine is as confmaking use of as triple-Inception, tright here is many likely a much more elegant method to tackle the difficulty.

Teasers and also exercises

The following exercises involve examining reasonably simple for-loops. The function is to make sure you have the right to confidently recognize what a for-loop looks choose, even if the code block to be executed appears pointless or pointlessly complex.

Fix these scripts

These straightforward for-loop examples all contain syntaxation errors. See if you have the right to spot them:

for x in range(5):print("hello world")for number_in range(5): print("hello world")for really_big_number in really_embiggened_range_of_nuumbers print("hello world")Try to predict the output of these scriptsThis is even more of a test to check out if you understand also variable assignment

a = "whatever"for x in range(42): a = xprint(a)You have the right to execute anypoint in a loop. Even math:

a = 0for x in range(3): a = a + x * 10print(a)What happens if we"ve defined a loop to run exactly 0 times:

a = 100for number in range(0): a = a + numberprint(a)This is actually just one more test of expertise variable assignment:

a = 100b = 200for number in range(3): b - a - number for number in range(100): a + b * numberprint(a)print(b)Just in instance you"re puzzled by the syntax – or more most likely, the real-civilization purpose of the manuscript above – first of all, programming doesn"t need to have a "real-world" objective, as far as the interpreter is pertained to. As long as the syntaxes is fine, the computer will certainly run the program, no issue just how meaningmuch less it is to the genuine world.

2nd, what you are meant to recognize is that whether it"s in a solitary for-loop or a loop-inside-a-loop – the statement, a + b does simply exactly that: it adds the contents of a and b together. That tbelow is no impact at the finish is a consequence of no variable assignment being done: i.e. the worths of a and also b are never before reassigned. Hence, the boring output at the finish.

For the objectives of this curriculum, I will certainly never before have actually you deliberately create a program this pointmuch less. But that"s not the suggest – you may accidentally compose a pointmuch less regime. Not being able to check out the logic error inside the for-loop is occasionally a result of not being comfortable with the for-loop syntaxation in the initially location.

Were those exercises too simple? I"ve deliberately made them easy. It"s only necessary that you understand also and also recognize the syntax of a for-loop statement. That"s not meant to be the complex component. But as soon as you compose facility programs that involve for-loops, you do not desire the standard syntax and also procedure of a for-loop to be a resource of confusion for you.

Moving on

Read the leskid on conditional-branching (i.e. if/elif/else statements).