Conditionals and loops

In Python we can use the if statement as follows:

if a>b:
    print(a)

In contrast to other programming languages Python does not use {} to declare the opening or the closing of an if statement. Python uses indentation (tab key or four spaces). Python’s indentation is a way to tell Python interpreter that a group of statements belong to a block of code. In the previous example the variable a will be printed if a is greater than b.

In the next piece of code the lines 2 and 3 will be executed if a is greater than b and the lines 5 and 6 will be executed if a is not greater than b. Indentation in Python matters!

if (a>b):
    print(a)
    print ("Hello")
else:
    print("b")
    print("Goodbye")

We can always examine more than 2 logical conditions with the use of elif (stands for else if ).

if (a>b):
    print(a)
elif (b>a):
    print(b)
else:
    print("Equals")

Python will create automatically an indent if we end the previous block of code with a colon “:”

A colon is used in conditionals (if statements) as well as in loops (while, for, etc) to declare which lines of code belong to a specific logical expression.

We can also combine logical expressions using the and or the or operator to create more interesting statements. In the following example line 2 will be executed if both of the expressions (age>4 and age <=10) are true.

if age > 4 and age <= 10:
    print('Best age to learn programming')

Loops

An if statement is useful if we need to check a logical statement once. If we want to keep executing a set of code bocks until a specific logical expression comes true, we have to use a loop.

while

The most common loop statement is the while. In the following example, the while statement will be true as long as the variable a is less than 10.

a=1
while (a<10):
    print(a)
    a = a+1

For loop

for i in range(10):
    name = input('What is your name?')
    if name == 'John':
        print('Hello John')

 

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.