Python Flow Controls & Loops
Python Flow Controls & Loops
if condition:
# Code to execute if condition is True
else statements: Used with if to specify code to execute when the condition is False.
if condition:
# Code to execute if condition is True
else:
# Code to execute if condition is False
if condition1:
# Code to execute if condition1 is True
elif condition2:
# Code to execute if condition2 is True
else:
# Code to execute if no conditions are True
Looping:
for loops: Used for iterating over a sequence (e.g., list, tuple, string) or any
iterable object.
numbers = [1, 2, 3, 4, 5]
In this example, we have a list of numbers, and the for loop iterates through each number in
the list. Inside the loop, it adds each number to the sum_of_numbers variable. After the loop
completes, it prints the sum of all the numbers in the list. When you run this code, you'll get
the following output:
while condition:
# Code to execute as long as the condition is True
password = "12345"
user_input = ""
while user_input != password:
user_input = input("Enter your password: ")
print("Access granted. Welcome!")
Loop control statements in Python, including break, continue, and pass, allow you to
modify the flow of loops (such as for and while) to achieve specific behaviors. Here's an
explanation of each with examples:
1. break:
o break is used to exit a loop prematurely, typically when a certain condition is
met.
o It terminates the loop and continues with the next code after the loop.
Example:
python
for num in range(1, 11):
if num == 5:
break # This will exit the loop when num is 5
print(num)
Output:
1
continue:
continue is used to skip the current iteration of a loop and continue with the next
iteration.
It allows you to bypass some parts of the loop based on a condition without exiting
the loop entirely.
Example:
python
for num in range(1, 11):
if num % 2 == 0:
continue # Skip even numbers
print(num)
Output:
1
3
5
7
9
pass:
pass is a null operation statement in Python. It doesn't do anything and is often used
as a placeholder when you need syntactically correct code but don't want any specific
action to be taken.
It's useful when you're working on the structure of your code and want to come back
later to fill in the details.
Example:
python
for i in range(5):
if i == 3:
pass # Placeholder for future code
else:
print(i)
Output:
3. 0
4. 1
5. 2
6. 4
In the break example, the loop exits when num is equal to 5. In the continue example, even
numbers are skipped, so only odd numbers are printed. In the pass example, the pass
statement acts as a placeholder, allowing the loop to continue without any action when i is
equal to 3.
These loop control statements provide flexibility in controlling the flow of your loops,
allowing you to customize the behavior of your code based on specific conditions or
requirements.
Default Parameters:
Default parameters in Python allow you to specify a default value for a function argument. If
the argument is not provided when calling the function, the default value will be used. This is
a useful feature when you want to make a function more flexible by providing some sensible
defaults.
In your example:
python
def power(base, exponent=2):
return base ** exponent
The exponent parameter has a default value of 2. So, if you call the power function with only
one argument:
python
result = power(5)
It will use the default value for exponent, and result will be 5 raised to the power of 2,
which is 25.
However, you can also provide a different value for exponent if you want to calculate the
power with a different exponent:
python
result = power(5, 3)
Default parameters are a powerful way to make functions more versatile and user-friendly by
allowing callers to omit some arguments when they are not needed.
Lambda Functions:
Lambda functions are indeed small, anonymous functions in Python, often used for simple
operations. They are sometimes referred to as "anonymous" because they don't have a name
like regular functions defined with the def keyword. Instead, they are defined using the
lambda keyword, followed by a list of parameters and an expression that gets evaluated and
returned as the result.
In your example:
python
multiply = lambda x, y: x * y
result = multiply(3, 4)
print(result)
You've created a lambda function called multiply that takes two arguments x and y and
returns their product. When you call multiply(3, 4), it returns 12, which is the result of
multiplying 3 and 4, and that result is stored in the result variable and printed.
python
def add(x, y):
return x + y
python
2. add = lambda x, y: x + y
3.
So, the choice between regular functions and lambda functions depends on the complexity of
the task and whether you need a named, reusable function or a simple, anonymous one-liner.
Recursion,
Recursion is a programming concept where a function calls itself in order to solve a problem.
In Python, you can create recursive functions just like any other function. Here's a simple
example of a recursive function to calculate the factorial of a number:
python
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
result = factorial(5)
print(result) # This will print 120, which is 5!
In this example, the factorial function calls itself with a smaller argument (n - 1) until n
reaches 0, at which point it returns 1. The recursion stops when the base case (n == 0) is
reached. This is a classic example of recursion in programming.
Recursion is a programming concept that's a bit like a puzzle solving itself. Imagine you have
a big problem, and you realize that it's very similar to a smaller version of the same problem.
So, instead of trying to solve the big problem directly, you decide to break it down into
smaller pieces.
So, you start with a big problem, like finding 5!, which you can break down like this:
5! =5 * 4!
4! =4 * 3!
3! =3 * 2!
2! =2 * 1!
1! =1 * 0!
Now, you can solve the base case, 0!, which is 1. Then you combine the results to get the
final answer:
1! =1 * 1=1
2! =2 * 1=2
3! =3 * 2=6
4! =4 * 6 = 24
5! =5 * 24 = 120
So, 5! is 120.
Recursion can be a powerful and elegant way to solve certain types of problems, but it's
essential to ensure that there's always progress towards the base case to avoid infinite
recursion.
Built-in Functions
Python provides a wide range of built-in functions to perform common tasks without the need
for you to write custom code. Here's a brief explanation of the functions you've mentioned in
your example:
1. len(): This function is used to determine the length (the number of elements) of a
sequence, such as a list, tuple, or string. In your example:
numbers = [5, 2, 8, 1]
length = len(numbers)
len(numbers) returns 4 because there are four elements in the numbers list.
2. max(): This function is used to find the maximum value within a sequence. In your
example:
numbers = [5, 2, 8, 1]
maximum = max(numbers)
max(numbers) returns 8 because it finds the largest value in the numbers list.
3. min(): This function is used to find the minimum value within a sequence. In your
example:
numbers = [5, 2, 8, 1]
minimum = min(numbers)
min(numbers) returns 1 because it finds the smallest value in the numbers list.
These built-in functions can save you time and effort when working with data in Python, as
they provide efficient and reliable ways to perform common operations.