Introduction

This is Part 5 of the Mastering Python for Blockchain series. This part will explain loops in Python-while, for, in and also the range( ) function.

I will suggest you to download the latest version of Python which will help you to practice coding and compiling programs. In case you do not have Python installed in your system you can use this link to online run your Python codes.

I also suggest you to visit the article here to learn the basic concepts of Blockchain.

Loops in Python

Python uses either while or for for creating loops or checking in iterations. It helps Python to iterate through a large list of data. To show iterations you need something to iterate over. Strings, lists, tuple and dictionaries are the things to iterate over or the iterables. We saw strings in Part 3 and Part 4 of Mastering Python for Blockchain series. We will learn about lists, tuples and dictionaries in the parts .

Loops in Python with while

The simplest looping mechanism in Python is while. Consider the example code below.

Note: As mentioned in our earlier parts, # is used to add comments.

  • The 1st line is the comment. We have to print all the numbers from 1 to 10.
  • The second line assigns the value of 1 to the variable x.
  • From the third line the while loop starts. It states that until the value of x is smaller than or equal to 10
    a) print the value of x (line 4)
    b) increment the value of x by 1(line 5). After incrementing Python will go back again to line 3, and the while loop is again executed.
  • The while loop will stop when the value of x is incremented from 10 to 11. Here the condition that x<=10 is not met, and the loop stops.

Output:

What will be the output of the following?

Cancel an infinite loop with break

  • break statement is used to break or stop a an infinite loop.
  • See the below example.
  • The above is an infinite loop. We have used the input( ) function here. This function will prompt you to type any sentence by displaying the command “Type any sentence to capitalize”.
  • We used the function capitalize( ) in the 3rd line. As we have read in Part 4 of Mastering Python for Blockchain series, the capitalize( ) function makes the first letter of the first word of the sentence in capital letter.
  • Now since this is a loop (while True:), this will keep on running like forever. The interpreter will keep you prompting “Type any sentence to capitalize:”. Once you type any sentence, it will make the first letter of the first word in capital letters.

Output:

  • This will go on continuously. What if we want to define an end to the loop. In order to stop an infinite loop, we use the break statement. See below.

Output:

  • Now there can be certain instances, where you run a while loop to find an object. When the object is found you use the break statement to stop the program.

Example, we are trying to find out an even number in the list list (defined in the line 1). As soon as we find the even number, the program stops by printing “We found the even number number”. See the output below:

However, say we did not have any even number in the list. What if the list was, list=[1,3,5,7,9]. In this case we can use an optional else statement to print something like “No even number found”. Check below.

Output:

Skip ahead with continue

Sometimes you do not want to break out of the loop, but just want to skip and move ahead to the next iteration. Like see the below code, which skips an even number, but squares any other number.

Check the comments added after the hash (#) sign in green. In line 4, we used the % operator. Check the operators we discussed in Part 1 of the Mastering Python for Blockchain series. It states that if the remainder of x divided by 2 is zero, i.e. if x is even. In this case, if x is even, continue. This will skip the iteration to the next one and will ask you to enter another number. See the output.

Output:

As you see, when we enter any number other than an even number, the code gives its square. But as we enter an even number, it simply skips and asks you to enter another number.

Check break use with optional else

We can use an optional else to check whether break has been implemented. This happens when we are trying to search an object in a data with break. If the object is not found then break is not implemented. In this case, an optional else is implemented.

Output:

Loops in Python with for and in

  • Check the below code, for printing all the letters of a word.

Output:

But there is a better way of writing this code in Python. Rather than using the while loop we can use for and in. Let’s see how.

Output:

Cancel with break

Similar to what we used in the while loop, break can also be used to stop a for loop for a specific condition.

Output:

Skip with continue

Again, similar to how we used in while loop, continue can be used in the for and in loop, to skip and continue with the next iteration.

Output:

Check break use with optional else

Similar to, as was used in the while loop, an optional else is implemented when break is not implemented in a for and in loop.

Output:

range( ) function

  • The range( ) function returns a sequence of numbers within a specified range without first having to create and store a large data structure such as a list or tuple.
  • Format: range(start,stop,step)
    start is from where the sequence will start. If nothing is given, it takes the default value of ‘0’ (zero)
    stop: The sequence of numbers printed will stop at one before stop.
    step: It defines how many places forward or backward the sequence will go from start.
  • Note: start and step can have default values as 0 and 1 respectively. stop does not have any default value and hence it needs to be always defined.

Output:

Output:

This is pretty much for this part. We will cover Tuples and Lists in the next part.

Some Practice Questions:

  1. Use the for loop to print the values of the list [3,4,6,7,8,9]
  2. Assign the value 7 to the variable big_number, and the value 1 to the variable number. Write a while loop that compares number with big_number. Print ‘too low’ if number is less than guess me. If number equals big_number, print ‘found it!’. If number is greater than big_number, print ‘oops’ and then exit the loop. Increment number at the end of the loop.
  3. Assign the value 5 to the variable guess_me. Use a for loop to iterate a variable called number over range(10). If number is less than guess_me, print ‘too low’. If it equals guess_me, print found it! and then break out of the for loop. If number is greater than guess_me, print ‘oops’ and then exit the loop.

Do comment me in case you are unable to solve any of the above. Happy reading:)

Leave a Reply