Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

Python Flow Controls & Loops

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Python Flow Controls & Loops

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Conditional Statements:

 if statements: Used for conditional execution of code blocks based on a specified


condition.

 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

 elif statements: Used to test multiple conditions in a chain.

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]

# Calculate the sum of all numbers in the list


sum_of_numbers = 0
for number in numbers:
sum_of_numbers += number

# Print the result


print("The sum of numbers in the list is:", sum_of_numbers)

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:

The sum of numbers in the list is: 15


while loops: Used to repeatedly execute a block of code as long as a specified condition
is True.

 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:

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)

In this case, result will be 5 raised to the power of 3, which is 125.

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.

In Python, you can create functions in two ways:

1. Regular Functions (Created with def):


o These functions have names, and you define them using the def keyword.
o They are suitable for more complex tasks and when you need to reuse the
function at multiple places in your code.
o They are often used when the function's logic involves multiple statements or
calculations.

python
 def add(x, y):
return x + y

 Lambda Functions (Created with lambda):

 These functions are anonymous (they don't have names).


 They are typically used for simple, one-line operations.
 They are often used when you need a function for a brief, specific purpose, especially
when you pass a function as an argument to another function or use it momentarily.

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.

Here's an easy way to understand recursion:


1. Base Case: You start with a problem that you can solve easily. This is called the base
case. In recursion, you always need a base case to stop the recursion and prevent it
from going on forever.
2. Recursive Case: You take your big problem and break it down into a smaller, simpler
version of the same problem. To solve this smaller problem, you use the same method
(the function calls itself), but now the problem is closer to the base case.
3. Progress Toward Base Case: With each recursive call, you move closer to the base
case. Eventually, you'll reach the base case, which is the smallest version of the
problem you can solve directly.
4. Combine Results: As you solve each smaller problem, you combine their results to
get the solution to the original, bigger problem.

Here's a classic example: calculating the factorial of a number.

 Base Case: The factorial of 0 is 1 (0! = 1).


 Recursive Case: To find the factorial of a number n, you can express it as n * (n-
1)!.

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.

You might also like