Loops and if-statements in Python

A in depth study about if-statements and loops in Python

Photo by AltumCode on Unsplash

Welcome back, fellow developers!🎉🎉

Here another beginners guide about statement and loops in Python, to proceed our in-depth learning of this beautiful programming language.

As always, there is an entire list about Python that I created here on Medium called PyWithMe. Come to take a look if you want to discuss about Python, you won’t regret it.

Statements

In computer programming, a statement is a syntactic unit of an imperative programming language that expresses some action to be carried out. A program written in such a language is formed by a sequence of one or more statements. A statement may have internal components, also called expressions.

So, a statement is a command that the programmer gives to the computer. For example: print("Hello, world!"). This command has a verb (“print”) and other details (what to print on the screen).

In this section we will analyze a particular statement: the if-statement, also called conditional.

If-statement (Conditionals)

In computer science, conditionals are commands for handling decisions. Specifically, conditionals perform different computations or actions depending on whether a programmer-defined boolean condition evaluates to true or false. In terms of control flow, the decision is always achieved by selectively altering the control flow based on some condition (apart from the case of branch predication).

Note: In computer science, the Boolean (sometimes shortened to Bool) is a data type that has one of two possible values (usually denoted true and false) which is intended to represent the two truth values of logic and Boolean algebra.

👉Here is a useful link if you want to know more about Boolean algebra.

To accomplish the goal of making decisions, the terminology that Python uses to create conditionals statements, in pseudocode, is this:

Pseudocode of if statement

This particular block of code tells a lot of things. First it tells us that just one block will be executed, the if one will be executed if the condition that we created results to be true. On the other hand, the else block will be executed if and only if that particular condition results to be false.

This is how we can tell to the compiler to take a decision. Now, let’s see an example.

In this example we asked to the compiler to print on the screen a sentence and to decide which sentence to print, based on the value of x.

More than two options

In the example above we just showed two possible options:

if (condition is True):
#Then do something....
else:
#Do something else....

Well, you have to consider that life is not that simple and more often we should say to our compiler to decide within a bunch of other options.

Lazy people could use just if statements to switch between options, for example:

x = 10
if (x > 5):
print("x is greater than 5")
if (x > 7):
print("x is greater than 7")
if (x < 12):
print("x is smaller than 12")
if (x > 9):
print("x is greater than 9")

Can you wonder what’s the result of these blocks of code?

Exactly! All of them!

I used Jupyter Notebook for this particular case, because I’m too lazy to open the Cmd Prompt

This happens because we didn’t say to the compiler to exclude some of these statements. But what happen if we want just one of them, excluding all the others?

In this particular case we can use elif statements, that stands for else-if.

As you can see the result is just the first one, the compiler excludes by himself the other ones and this thanks to elif keyword.

Nested if and else statements

Sometimes could happen that we need more if and else statements, in this particular case we can talk about: nested statements.

I think that an example could give us more understanding about this topic.

As you can notice, this particular blocks of code are called nested because each block is inside another block, like birds’ nests.

In our case we asked to the compiler to found the right value of x, the compiler goes through every nested statement and in the end it founds the correct one.

Obviously this isn’t “well coding”, because there are too many options, but it’s very useful to understand this topic. Remember that nested if and else statements could be long as you want, but shorter is better.

Loops Statements

In Python, a loop is a statement that contains instructions that continually repeats until a certain condition is reached.

Loops help us remove the redundancy of code when a task has to be repeated several times. With the use of loops, we can cut short those hundred lines of code to a few. Suppose you want to print the text Hello, World! 10 times. Rather than writing a print statement 10 times, you can make use of loops by indicating the number of repetitions needed.

But before to dive in the various examples, you have to know that there are three main types of loops in Python:

  1. For loops
  2. While loops
  3. Nested loops

For loops

A for loop is used to iterate over a sequence like lists, type, dictionaries, sets, or even strings.

Loop statements will be executed for each item of the sequence. In our example we will use the function range(). The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.

So, if we want to print ten times the words “Hello, World!” like we said before, how could we write that?

Easy, don’t you?

Note: The range() function starts from 0 (zero) and it increments by 1 each repetition. So you should count in this way: 0, 1, 2, 3,…., 9, that are ten times.

While loops

While loops are a bit more complicated. It continually executes the code as long as the given condition is TRUE. It first checks the condition and then jumps into the instructions.

For example, we want to print on the screen a sentence 5 times using a while loop.

As you can see, the while loop checks the condition, if it’s True then continues the flow and print the message, then add 1 to the original value of x. When the x reach the value 10, the while loop checks for the condition that returns False, at that point it stops the flow.

Nested loops

Nested loops mean using a loop inside another loop. We can use any type of loop inside any type of loop. We can use a while loop inside for loop, a for loop inside a while loop, a while loop inside a while loop, or a for loop inside a for loop. Fantasy is our ally.

Let’s try to make an example. We want to print on the screen all the even numbers between 1 and 10 included.

In this example we used a for loop to count from 1 to 10 included and a while loop to check if the number in the sequence is even or not using the operator % (modulus). Basically with the modulus operator (%) we’re trying to ask to the compiler to check if the remainder by dividing the number by two is zero. After checking if the parity condition is satisfied, we print the message {number} is an even number, where {number} is replaced with the effective number by the format() function that we saw in this article about strings and formatting.

And this is it for now about if and else statements and loops in Python. I hope that you enjoyed the article and that you found it useful.

Don’t forget to save this list about Python and to follow me for further updates about beginners tutorial in Python. See ya!! 🥂

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store