Published on

Python Control Structures - Mastering the Art of Flow

Authors

Introduction

Before we dive deep into Python's control structures, let's start with the fundamental concept of sequential execution. In Python, like in most programming languages, code is executed sequentially from top to bottom. This means that each line of code is executed one after the other, in the order it appears.

Decision making in the anticipation of conditions occuring during the execution of a program and specified action taken according to the conditions. Python programming language provides the following Decision Control Statements are:

if

The if statement contains a logical expression using which the data is compared and a decision is made based on the result of the comparision.

Syntax:

main.py

  if(expression):
    statement(s)
  # Note: In python statements in a block are uniformly indented after : symbol.

Flowchart

if-statement

Example

main.py

  a = int(input("Enter a value: "))
  b = int(input("Enter b value: "))
  if(a>b):
    print("Inside of if-block")
    print(f"Largest element is: {a}")
  print("Outside of if-block")

  ''' output: 
  Enter a value: 5
  Enter b value: 2
  Inside of if-block
  Largest element is: 5
  Outside of if-block
  '''

if-else

An else statement can be combined with an if-statement. An else statement contains a block of code that executes if the conditional expression in the if-statement resolves to 0 or a False value.

Syntax

main.py

  if(expression):
    statement(s)
  else:
    statement(s)

Flowchart

if-else-statement

Example

main.py

  a = int(input("Enter a value: "))
  b = int(input("Enter b value: "))
  if(a > b):
    print("Inside of if-block")
    print(f"Largest element is: {a}")
  else: 
    print("Inside of else-block")
    print(f"Largest element is: {b}")
  print("Outside of if-else-block")

  ''' Output:
    Enter a value: 5
    Enter b value: 2
    Inside of if-block
    Largest element is: 5
    Outside of if-else-block
    
    Enter a value: 2
    Enter b value: 4
    Inside of else-block 
    Largest element is: 4
    Outside of if-else-block
  '''

if-elif-else

The elif statement allows you to check multiple expressions for True and execute a block of code as soon as one of the condition evaluates to True.

Syntax

main.py

if(expression1):
  statement(s)
elif (expression2):
  statement(s)
elif (expression3):
  statement(s)
else:
  statement(s)

Flowchart

if-else-statement

Example

main.py

hours = int(input("Enter time in hours: "))
if(hours>=6 and hours<12):
  print("Good Morning :)")
elif (hours>=12 and hours<16):
  print("Good Afternoon :)")
elif (hours>=16 and hours<19):
  print("Good Evening :)")
else:
  print("Good Night :>")
  
''' Output:
Enter time in hours: 15
Good Afternoon :)
'''

nested if

Nested if statements are an if statement inside another if statement.

Syntax

main.py

  if(expression):
    if(expression):
      statement(s)
  else:
    statement(s)

Flowchart

if-else-statement

Example

main.py

  a = 5
  b = 10
  c = 15
  if a > b:
    if a > c:
        print("a value is big")
    else:
        print("c value is big")
  elif b > c:
      print("b value is big")
  else:
      print("c is big")
  
  # output: c is big

Single Statement Suites

If the suits if an if clause consists only of a single line, it may go on the same line as the header statement.

main.py

  num1 = int(input("Enter first number 1: "))
  num2 = int(input("Enter second number 2: "))

  if(num1 > num2): print(f'{num1} is greatest number')
  else: print(f"{num2} is greatest number")

  ''' Output:
  Enter first number 1: 5
  Enter second number 2: 2
  5 is greatest number
  '''

Conclusion

In this journey through Python control structures, we've explored the foundational concepts of sequential execution, conditional statements, looping structures, and exception handling. Armed with this knowledge, you have the tools to write more robust and efficient Python code.

Now, it's time to put your skills to the test and embark on your own Python programming adventures.

FAQs

  1. What is the difference between 'if' and 'elif' in Python?

'if' is used to check a single condition, while 'elif' is used to specify additional conditions to check if the previous ones are False.

  1. When should I use a 'for' loop in Python?

Use a 'for' loop when you know how many times you want to execute a block of code, such as iterating over a list or range.

  1. What is the purpose of the 'try', 'except', and 'finally' blocks in Python?

The 'try' block contains code that may raise an exception, 'except' handles the exception, and 'finally' contains code that always executes, regardless of whether an exception occurred or not.

  1. Can I nest control structures in Python?

Yes, you can nest control structures like 'if' statements inside 'for' or 'while' loops to create more complex logic.

  1. Where can I learn more about Python control structures?

To dive deeper into Python control structures, consider exploring the official Python documentation and various online tutorials.