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 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
StatementThe 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
StatementThe 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
StatementThe 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 are used to repeat a block of code multiple times. Python provides two types of loops: for
loops and while
loops.
for
LoopThe 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
LoopThe 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 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.
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)."""Docstring"""
is a multi-line string that provides a brief description of the function (optional but recommended).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!
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
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.
The scope of a variable or function refers to the region of the code where it is accessible. Python has several types of scope:
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)
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:
When Python tries to resolve a name (e.g., a variable or function), it searches the namespaces in the following order:
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.
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.
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.
To get started with CodeWars, follow these steps: