23
Introduction to Control Flow and Functions in Python.
You use the if statement to execute a block of code based on a specified condition.
The syntax of the if statement is as follows:
The syntax of the if statement is as follows:
if condition:
if-block
The if statement checks the condition first.
If the condition evaluates to True, it executes the statements in the if-block. Otherwise, it ignores the statements.
Example
If the condition evaluates to True, it executes the statements in the if-block. Otherwise, it ignores the statements.
Example
marks = input('Enter your score:')
if int(marks) >= 40:
print("You have passed")
Output
Enter your score:46
You have passed
Used when you want to perform an action when a condition is True and another action when the condition is False.
Here is the syntax
Here is the syntax
if condition:
if-block;
else:
else-block;
An example to illustrate how to use the if...else statement:
marks = input('Enter your score:')
if int(age) >= 40:
print("You have passed.")
else:
print("You have failed.")
It is used to check multiple conditions and perform an action accordingly.
The elif stands for else if.
The elif stands for else if.
Here is the syntax:
if if-condition:
if-block
elif elif-condition1:
elif-block1
elif elif-condition2:
elif-block2
...
else:
else-block
Example
marks = input('Enter your score:')
your_marks = int(marks)
if your_marks >= 70:
print("Your grade is A")
elif your_marks >= 60:
print("Your grade is B")
else:
print("null")
Output
Enter your score:70
Your grade is A
To execute a block of code multiple times in programming you use for loop
Here is the syntax:
Here is the syntax:
for index in range(n):
statement
for index in range(5):
print(index)
Output
0
1
2
3
4
Specifying the starting value for the sequence
The range() function allows you to specify the starting number like this:
The range() function allows you to specify the starting number like this:
range(start,stop)
Example
for index in range(1, 4):
print(index)
Output
1
2
3
4
Specifying the increment for the sequence
By default, the range(start, stop) increases the start value by one in each loop iteration.
To specify increment sequence, use the following syntax:
By default, the range(start, stop) increases the start value by one in each loop iteration.
To specify increment sequence, use the following syntax:
range(start, stop, step)
The following example shows all odd numbers from 0 to 10:
for index in range(0, 11, 2):
print(index)
output
0
2
4
6
8
10
Using Python for loop to calculate the sum of a sequence
The following example uses the for loop statement to calculate the sum of numbers from 1 to 50:
The following example uses the for loop statement to calculate the sum of numbers from 1 to 50:
sum = 0
for num in range(51):
sum += num
print(sum)
Output
1275
Python while statement allows you to execute a code block repeatedly as long as a condition is True
Here is the syntax:
Here is the syntax:
while condition:
body
max = 5
counter = 0
while counter < max:
print(counter)
counter += 1
Output
0
1
2
3
4
for index in range(0, 11):
print(index)
if index == 3:
break
Output
0
1
2
3
FUNCTIONS IN PYTHON
A function is a block of organized, reusable code that is used to perform a single, related action.
Here are simple rules to define a function in Python.
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
When you want to use a function, you just need to call it. A function call instructs Python to execute the code inside the function.
A function can perform a task like the greet() function. Or it can return a value. The value that a function returns is called a return value.
To return a value from a function, you use the return statement inside the function body.
To return a value from a function, you use the return statement inside the function body.
Parameter and argument can be used for the same thing but from functions perspectives;
A parameter is the variable listed inside the parentheses in the function definition.
An argument is the value that are sent to the function when it is called.
From this example;
def addNumbers(a, b):
sum =a + b
print("The sum is " ,sum)
addNumbers(2,5)
A function can have zero, one, or multiple parameters.
The following example defines a function called sum() that calculates the sum of two numbers:
The following example defines a function called sum() that calculates the sum of two numbers:
def sum(a, b):
return a + b
total = sum(1,20)
print(total)
output
21
In the above example, the sum() function has two parameters a and b, and returns the sum of them. Use commas to separate multiple parameters.
Recursive Function Examples
1.Count Down to Zero
1.Count Down to Zero
def countdown(n):
print(n)
if n == 0:
return # Terminate recursion
else:
countdown(n - 1) # Recursive call
countdown(5)
Output
5
4
3
2
1
0
2.Calculating the sum of a sequence
Recursive functions makes a code shorter and readable.
Suppose we want to calculate the sum of sequence from 1 to n instead of using for loop with range() function we can use recursive function.
Recursive functions makes a code shorter and readable.
Suppose we want to calculate the sum of sequence from 1 to n instead of using for loop with range() function we can use recursive function.
def sum(n):
if n > 0:
return n + sum(n - 1)
return 0
result = sum(100)
print(result)
A lambda function is a small anonymous function that can take any number of arguments, but can only have one expression.
Syntax
Syntax
lambda arguments : expression
Examples:
def times(n):
return lambda x: x * n
double = times(2)
result = double(2)
print(result)
result = double(3)
print(result)
From the above example times() function returns a function which is a lambda expression.
Here is a simple syntax for a basic python decorator
def my_decorator_func(func):
def wrapper_func():
# Do something before the function.
func()
# Do something after the function.
return wrapper_func
To use a decorator ,you attach it to a function like you see in the code below.
@my_decorator_func
def my_func():
pass
23