Session 2: Control Flow and Functions

Instructor : Seyed Sadjad Abedi-Shahri

Control flow statements in Python allow you to control the order of execution of your code based on certain conditions or loops. These statements are essential for creating dynamic and flexible programs.

Conditional Statements

Conditional statements allow you to execute different blocks of code based on certain conditions. Python uses the if, elif (else if), and else statements for this purpose.

if Statement

The if statement executes a block of code if the specified condition is True.

1x = 5
2
3if x > 0:
4   print("x is positive")

elif Statement

The elif statement allows you to check for additional conditions if the previous conditions were False.

1x = 0
2
3if x > 0:
4    print("x is positive")
5elif x < 0:
6    print("x is negative")
7else:
8    print("x is zero")

else Statement

The else statement is executed if all the previous conditions in the if and elif statements were False.

1age = 18
2
3if age < 13:
4    print("You are a child")
5elif age < 20:
6    print("You are a teenager")
7else:
8    print("You are an adult")

Loops

Loops are used to repeat a block of code multiple times. Python provides two types of loops: for loops and while loops.

for Loop

The for loop is used to iterate over a sequence (such as a list, tuple, string, or range) or other iterable objects.

1fruits = ["apple", "banana", "cherry"]
2
3for fruit in fruits:
4    print(fruit)

You can also use the range() function to generate a sequence of numbers for the for loop.

1for i in range(5):
2    print(i)  # Output: 0 1 2 3 4

while Loop

The while loop executes a block of code as long as the specified condition is True.

1count = 0
2while count < 5:
3    print(count)
4    count += 1  # Increment the counter

Loops can be nested (one loop inside another loop) to create more complex patterns or iterate over multi-dimensional data structures.

1for i in range(3):
2    for j in range(2):
3        print(f"({i}, {j})")

Functions

Functions are reusable blocks of code that perform a specific task. They help organize code into logical units, improve code readability, and promote code reuse. In Python, functions are defined using the def keyword, followed by the function name, parentheses for arguments, and a colon.

Defining Functions

Here’s the basic syntax for defining a function:

1def function_name(parameters):
2   """
3   Docstring: A brief description of what the function does.
4   """
5   # Function body
6   # Code to be executed
7   return value
  • def is the keyword used to define a function.
  • function_name is the name you give to the function (follow naming conventions).
  • parameters are optional inputs that the function can accept (separated by commas).
  • The """Docstring""" is a multi-line string that provides a brief description of the function (optional but recommended).
  • The function body is the block of code that will be executed when the function is called.
  • The return statement is used to return a value from the function (optional).

Example:

1def greet(name):
2    """
3    Prints a greeting message with the provided name.
4    """
5    print(f"Hello, {name}!")
6
7greet("Alice")  # Output: Hello, Alice!

Calling Functions

To use a function, you need to call it by its name, followed by parentheses and any required arguments.

1result = my_function(argument1, argument2)

Functions can return values using the return statement, which can be assigned to variables or used in expressions.

1def add_numbers(a, b):
2    """
3    Returns the sum of two numbers.
4    """
5    return a + b
6
7sum = add_numbers(3, 5)
8print(sum)  # Output: 8

Scope and Namespaces

In Python, variables and functions have a scope, which determines their visibility and accessibility within the program. Understanding scope and namespaces is crucial for managing variable names and avoiding naming conflicts.

Scope

The scope of a variable or function refers to the region of the code where it is accessible. Python has several types of scope:

  1. Local Scope: Variables defined within a function are local to that function and cannot be accessed outside of it. Their scope is limited to the function in which they are defined.
  1. Global Scope: Variables defined outside of any function or class are global and can be accessed from anywhere in the program, including within functions.
  2. Built-in Scope: Names that are part of the Python language itself, such as print, len, and range, have a built-in scope and are always available.

Example:

1x = 10  # Global variable
2
3def my_function():
4    y = 5  # Local variable
5    print(x)  # Accessing global variable
6    print(y)
7
8my_function()  # Output: 10, 5
9print(y)  # Error: y is not defined (outside the function scope)

Namespaces

While scope determines the visibility and accessibility of variables and functions, namespaces are mapping structures that associate names (identifiers) with objects (variables, functions, etc.). Python maintains several namespaces:

  • Built-in Namespace: Contains names of built-in functions, exceptions, and other objects. This namespace is always available.
  • Global Namespace: Contains names defined at the top level of a module or script. Variables and functions defined outside any function or class reside in this namespace.
  • Local Namespace: Contains names defined inside a function or class. Variables and functions defined within a function or class reside in this namespace.

When Python tries to resolve a name (e.g., a variable or function), it searches the namespaces in the following order:

  1. Local Namespace
  2. Enclosing Namespaces (if nested functions or classes)
  3. Global Namespace
  4. Built-in Namespace

The scope of a variable or function determines which namespace it belongs to and where it can be accessed. The namespaces themselves are the structures that store and map these names to their corresponding objects.

Introducing CodeWars

CodeWars is an educational online platform that helps developers improve their coding skills through practice and gamification. It provides a vast collection of coding challenges, also known as “katas”, which cover a wide range of programming languages and concepts.

What are Katas?

Katas are coding challenges that range in difficulty from beginner to expert level. Each kata presents a problem statement and a set of requirements that you must fulfill by writing code that passes a series of test cases. Katas are designed to help you practice your problem-solving skills, learn new language features, and improve your coding proficiency.

Getting Started with CodeWars

To get started with CodeWars, follow these steps:

  1. Sign Up: Visit the CodeWars website (https://www.codewars.com) and create an account.
  2. Choose a Language: Select the programming language you want to practice. CodeWars supports many popular languages, including Python, Java, JavaScript, C#, and more.
  1. Browse Katas: Explore the available katas by difficulty level or topic. You can filter katas based on your preferences or search for specific keywords.
  2. Attempt a Kata: Click on a kata to view its problem statement and requirements. CodeWars provides an online code editor where you can write and test your solution.
  1. Submit Your Solution: Once you’ve written your code, submit it to the CodeWars platform. Your solution will be tested against a set of test cases, and you’ll receive feedback on whether it passed or failed.
  2. Learn from Others: CodeWars allows you to view other users’ solutions to the same kata. You can learn from these solutions and gain insights into different problem-solving approaches.
  1. Optionally, You can join the Clan “Scicho” by setting this name as clan name in your profile. You can also follow the instructor using this Link:

Sadjad Profile Badge

  1. There is also a collection of katas that most fit your current proficiency:

Python Primer - Scicho

Tutorial Videos

  1. Introduction to Codewars for Learning Python Programming

  2. How to Use Codewars Platform

Questions?

Email

Telegram