[go: up one dir, main page]

0% found this document useful (0 votes)
11 views39 pages

Condional Statement N Loops

This document provides a comprehensive overview of conditional statements and loops in Python, focusing on their syntax and usage. It covers the 'if', 'else', and 'elif' statements, logical operators, nested conditions, and best practices for writing readable code. Additionally, it discusses advanced topics such as ternary conditional expressions, membership testing with 'in', and floating-point comparisons.

Uploaded by

SAMBHAV JHA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views39 pages

Condional Statement N Loops

This document provides a comprehensive overview of conditional statements and loops in Python, focusing on their syntax and usage. It covers the 'if', 'else', and 'elif' statements, logical operators, nested conditions, and best practices for writing readable code. Additionally, it discusses advanced topics such as ternary conditional expressions, membership testing with 'in', and floating-point comparisons.

Uploaded by

SAMBHAV JHA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

CONDITIONAL STATEMENTS

&
LOOPS PYTHON
(BASIC)
Introduction to Conditional Statements

Conditional statements are an essential concept in


programming languages, allowing developers to control the flow
of code execution based on specific conditions. In Python,
conditional statements are fundamental constructs that enable
decision-making within programs. They play a crucial role in
implementing logic, making choices, and handling various
scenarios efficiently. This academic guide explores conditional
statements in Python, providing a comprehensive overview and
practical examples to enhance your understanding.

Python, like many programming languages, uses conditional


statements to control the flow of execution based on certain
conditions.

Conditional statements allow you to make decisions in your


code and execute different blocks of code based on whether a
given condition is true or false.

The most common conditional statement in Python is the "if"


statement, but there are also "elif" (else if) and "else"
statements to provide alternative paths for the code to take.

The "if" Statement:

The "if" statement is used to check whether a given condition is


true or false.

The syntax of an "if" statement is as follows:

if condition:

# Code block to be executed if the condition is true

The condition can be any expression that evaluates to either


True or False.

1|Page
If the condition is true, the indented code block under the "if"
statement is executed.

If the condition is false, the code block is skipped, and the


program continues to the next statement after the "if" block.

Example of "if" Statement:

Let's consider an example of using the "if" statement to check if


a variable "x" is greater than 5:

x=7

if x > 5:

print("x is greater than 5")

The "else" Statement:

The "else" statement is used to provide an alternative code block


when the condition of the "if" statement is false.

It does not require a condition, and it is executed when all


previous conditions are false.

The syntax of the "else" statement is as follows:

if condition:

# Code block to be executed if the condition is true

else:

# Code block to be executed if the condition is false

You can use the "else" statement to handle the default case
when none of the conditions in the "if" or "elif" blocks are true.

Example of "else" Statement:

Continuing from the previous example, let's add an "else" block


to handle the case when "x" is not greater than 5:

2|Page
x=3

if x > 5:

print("x is greater than 5")

else:

print("x is less than or equal to 5")

The "elif" Statement:

The "elif" (short for "else if") statement allows you to check
multiple conditions one after another.

It is only checked if the previous "if" or "elif" conditions are false.

You can use multiple "elif" statements to provide additional


conditions to be checked.

The syntax of the "elif" statement is as follows:

if condition1:

# Code block to be executed if condition1 is true

elif condition2:

# Code block to be executed if condition2 is true and


condition1 is false

elif condition3:

# Code block to be executed if condition3 is true and all


previous conditions are false

else:

# Code block to be executed if all previous conditions are false

3|Page
Example of "elif" Statement:

Let's consider an example where we use "elif" to check if a


number is positive, negative, or zero:

x = -2

if x > 0:

print("x is positive")

elif x < 0:

print("x is negative")

else:

print("x is zero")

Logical Operators:

Logical operators are used to combine multiple conditions in


conditional statements.

Python has three logical operators: "and", "or", and "not".

• "and" requires both conditions to be true for the entire


expression to be true.
• "or" requires at least one condition to be true for the entire
expression to be true.
• "not" negates the result of a condition, making "True" into
"False" and vice versa.

Example of Logical Operators:


Let's use logical operators to check if a number is both positive
and even:

x=6

if x > 0 and x % 2 == 0:

print("x is a positive even number")


4|Page
Nesting Conditional Statements:

You can nest conditional statements inside each other to handle


more complex scenarios.

This means having one conditional statement inside another's


code block.

Example of Nested Conditional Statements:

Let's consider an example where we check if a number is positive


and even, positive and odd, negative and even, or negative and
odd:

x=5

if x > 0:

if x % 2 == 0:

print("x is a positive even number")

else:

print("x is a positive odd number")

else:

if x % 2 == 0:

print("x is a negative even number")

else:

print("x is a negative odd number")

Using Parentheses to Control Evaluation Order:

Parentheses can be used to group conditions and control the


evaluation order.

This is especially helpful when dealing with complex conditions


involving multiple logical operators.

5|Page
Example of Using Parentheses:

Let's check if a number is either positive and even or negative


and odd:

x=5

if (x > 0 and x % 2 == 0) or (x < 0 and x % 2 != 0):

print("x satisfies the condition")

Ternary Conditional Expression:

Python supports a compact way of expressing simple conditional


expressions known as the ternary conditional expression.

It allows you to write a single line of code to assign a value based


on a condition.

Syntax of Ternary Conditional Expression:

The syntax of the ternary conditional expression is as follows:

variable = value_if_true if condition else value_if_false

Example of Ternary Conditional Expression:

Let's use the ternary conditional expression to assign a grade


based on a student's score:

score = 75

grade = "Pass" if score >= 60 else "Fail"

print(grade)

Avoiding Assignment Mistakes:

When using conditional statements, be cautious not to use the


assignment operator "=" when comparing values in conditions.

Use "==" to check for equality in conditions.

Example of Avoiding Assignment Mistake:

6|Page
Incorrect code:

x = 10

if x = 10: # Incorrect: using assignment instead of comparison

print("x is equal to 10")

Using "is" for Object Identity:

Python has the "is" operator to check for object identity, which
means checking if two variables refer to the same object.

It is different from "==" since "is" compares the memory


addresses of objects, not their values.

Example of "is" Operator:

Let's check if two variables refer to the same object:

x = [1, 2, 3]

y=x

if x is y:

print("x and y refer to the same list object")

Floating-Point Comparisons:

Be cautious when using floating-point numbers in conditions due


to potential precision issues.

Floating-point arithmetic may lead to small rounding errors,


causing unexpected results in comparisons.

Example of Floating-Point Comparisons:

7|Page
Let's compare two floating-point numbers:

a = 0.1 + 0.1 + 0.1

b = 0.3

if a == b:

print("a is equal to b")

else:

print("a is not equal to b")

Using "in" and "not in" Operators:

Python allows you to use the "in" and "not in" operators to
check for membership in collections like lists, tuples, strings, etc.

They are useful for checking if an element exists in a collection.

Example of "in" Operator:

Let's check if an item exists in a list:

my_list = [1, 2, 3, 4, 5]

item = 3

if item in my_list:

print("Item is present in the list")

Using Conditional Statements in List Comprehensions:

Python allows you to use conditional statements inside list


comprehensions and generator expressions.

This allows you to filter and modify elements based on certain


conditions.

8|Page
Example of List Comprehension with Condition:

Let's create a list of squared numbers for even values from 0 to


9:

squared = [x**2 for x in range(10) if x % 2 == 0]

print(squared)

Using Conditional Statements in String Formatting:

You can use conditional expressions within string formatting to


display different results based on conditions.

Example of String Formatting with Condition:

Let's use a conditional expression to format a string based on a


score:

score = 75

result = "Pass" if score >= 60 else "Fail"

print(f"The result is: {result}")

Using "pass" Statement:

The "pass" statement is a no-op statement in Python, meaning


it does nothing.

It is often used as a placeholder when defining an empty code


block during development.

Example of "pass" Statement:

Let's use the "pass" statement in an "if" block:

x = 10

if x < 5:

pass # Do nothing if x is less than 5

9|Page
Best Practices for Readable Code:

Use meaningful variable names to make your code more


readable and self-explanatory.

Write clear and concise conditions to avoid confusion and bugs


in your code.

Avoid creating deeply nested conditional structures to maintain


code readability.

Make use of comments to explain complex conditions or


reasoning behind decisions.

Conclusion:

Conditional statements in Python are essential for making


decisions and controlling the flow of your code based on specific
conditions.

They allow you to execute different code blocks based on


whether a condition is true or false.

The "if", "else", and "elif" statements provide different paths for
the code to take, depending on the conditions.

Logical operators "and", "or", and "not" allow you to combine


multiple conditions for more complex evaluations.

Nested conditional statements provide flexibility in handling


complex scenarios.

Using parentheses can control the evaluation order of conditions,


especially in complex expressions.

Ternary conditional expressions offer a compact way to assign


values based on simple conditions.

Be cautious with floating-point comparisons due to potential


precision issues.

10 | P a g e
The "in" and "not in" operators help check for membership in
collections.

You can use conditional statements in list comprehensions and


string formatting for filtering and formatting purposes.

Following best practices for writing readable code will make your
programs more maintainable and easier to understand.

The "if" Statement:

The "if" statement is the most fundamental conditional


statement in Python.

It allows us to execute a block of code if a specified condition is


true.

The basic syntax of the "if" statement is:

if condition:

# Code block to be executed if the condition is true

2. Example of the "if" Statement:

Let's consider a simple example to understand the "if"


statement:

x = 10

if x > 5:

print("x is greater than 5")

3. The "else" Statement:

The "else" statement allows us to provide an alternative code


block to be executed when the condition of the "if" statement is
false.

It does not require a condition, and it is executed when all


previous conditions are false.

11 | P a g e
The syntax of the "else" statement is:

if condition:

# Code block to be executed if the condition is true

else:

# Code block to be executed if the condition is false

4. Example of the "else" Statement:

Continuing from the previous example, let's add an "else" block


to handle the case when "x" is not greater than 5:

x=3
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
5. The "elif" Statement:

The "elif" (else if) statement allows us to check multiple


conditions one after another.

It is only checked if the previous "if" or "elif" conditions are false.

You can use multiple "elif" statements to provide additional


conditions to be checked.

The syntax of the "elif" statement is:

if condition1:

# Code block to be executed if condition1 is true

elif condition2:

# Code block to be executed if condition2 is true and


condition1 is false

12 | P a g e
elif condition3:

# Code block to be executed if condition3 is true and all


previous conditions are false

else:

# Code block to be executed if all previous conditions are false

6. Example of the "elif" Statement:

Let's consider an example where we use "elif" to check if a


number is positive, negative, or zero:

x = -2

if x > 0:

print("x is positive")

elif x < 0:

print("x is negative")

else:

print("x is zero")

7. Logical Operators:

Logical operators are used to combine multiple conditions in


conditional statements.

Python has three logical operators: "and", "or", and "not".

"and" requires both conditions to be true for the entire


expression to be true.

"or" requires at least one condition to be true for the entire


expression to be true.

"not" negates the result of a condition, making "True" into


"False" and vice versa.

13 | P a g e
8. Example of Logical Operators:

Let's use logical operators to check if a number is both positive


and even:

x=6

if x > 0 and x % 2 == 0:

print("x is a positive even number")

9. Nesting Conditional Statements:

You can nest conditional statements inside each other to handle


more complex scenarios.

This means having one conditional statement inside another's


code block.

10. Example of Nested Conditional Statements:

Let's consider an example where we check if a number is positive


and even, positive and odd, negative and even, or negative and
odd:

x=5
if x > 0:
if x % 2 == 0:
print("x is a positive even number")
else:
print("x is a positive odd number")
else:
if x % 2 == 0:
print("x is a negative even number")
else:

14 | P a g e
print("x is a negative odd number")
11. Using Parentheses to Control Evaluation Order:

Parentheses can be used to group conditions and control the


evaluation order.

This is especially helpful when dealing with complex conditions


involving multiple logical operators.

12. Example of Using Parentheses:

Let's check if a number is either positive and even or negative


and odd:

x=5

if (x > 0 and x % 2 == 0) or (x < 0 and x % 2 != 0):

print("x satisfies the condition")

13. Ternary Conditional Expression:

Python supports a compact way of expressing simple conditional


expressions known as the ternary conditional expression.

It allows you to write a single line of code to assign a value based


on a condition.

14. Syntax of Ternary Conditional Expression:

The syntax of the ternary conditional expression is as follows:

variable = value_if_true if condition else value_if_false

15. Example of Ternary Conditional Expression:

Let's use the ternary conditional expression to assign a grade


based on a student's score:

score = 75

grade = "Pass" if score >= 60 else "Fail"

print(grade)

15 | P a g e
16. Avoiding Assignment Mistakes:

When using conditional statements, be cautious not to use the


assignment operator "=" when comparing values in conditions.

Use "==" to check for equality in conditions.

17. Example of Avoiding Assignment Mistake:

Incorrect code:

x = 10

if x = 10: # Incorrect: using assignment instead of comparison

print("x is equal to 10")

18. Using "is" for Object Identity:

Python has the "is" operator to check for object identity, which
means checking if two variables refer to the same object.

It is different from "==" since "is" compares the memory


addresses of objects, not their values.

19. Example of "is" Operator:

Let's check if two variables refer to the same object:

x = [1, 2, 3]

y=x

if x is y:

print("x and y refer to the same list object")

20. Floating-Point Comparisons:

Be cautious when using floating-point numbers in conditions due


to potential precision issues.

16 | P a g e
Floating-point arithmetic may lead to small rounding errors,
causing unexpected results in comparisons.

21. Example of Floating-Point Comparisons:

Let's compare two floating-point numbers:

a = 0.1 + 0.1 + 0.1

b = 0.3

if a == b:

print("a is equal to b")

else:

print("a is not equal to b")

22. Using "in" and "not in" Operators:

Python allows you to use the "in" and "not in" operators to check
for membership in collections like lists, tuples, strings, etc.

They are useful for checking if an element exists in a collection.

23. Example of "in" Operator:

Let's check if an item exists in a list:

my_list = [1, 2, 3, 4, 5]

item = 3

if item in my_list:

print("Item is present in the list")

24. Using Conditional Statements in List Comprehensions:

Python allows you to use conditional statements inside list


comprehensions and generator expressions.

This allows you to filter and modify elements based on certain


conditions.

17 | P a g e
25. Example of List Comprehension with Condition:

Let's create a list of squared numbers for even values from 0 to


9:

squared = [x**2 for x in range(10) if x % 2 == 0]

print(squared)

26. Using Conditional Statements in String Formatting:

You can use conditional expressions within string formatting to


display different results based on conditions.

27. Example of String Formatting with Condition:

Let's use a conditional expression to format a string based on a


score:

score = 75

result = "Pass" if score >= 60 else "Fail"

print(f"The result is: {result}")

28. Using "pass" Statement:

The "pass" statement is a no-op statement in Python, meaning


it does nothing.

It is often used as a placeholder when defining an empty code


block during development.

29. Example of "pass" Statement:

Let's use the "pass" statement in an "if" block:

x = 10

if x < 5:

pass # Do nothing if x is less than 5

30. Best Practices for Readable Code:

18 | P a g e
• Use meaningful variable names to make your code more
readable and self-explanatory.
• Write clear and concise conditions to avoid confusion and
bugs in your code.
• Avoid creating deeply nested conditional structures to
maintain code readability.
• Make use of comments to explain complex conditions or
reasoning behind decisions.

Conclusion:

Conditional statements in Python are essential for making


decisions and controlling the flow of your code based on specific
conditions. They provide powerful tools to handle different
scenarios efficiently. The "if", "else", and "elif" statements allow
you to create branching logic, while logical operators enable you
to combine multiple conditions. Nesting conditional statements
provides flexibility in handling complex scenarios, and the use of
parentheses ensures the correct evaluation order. The ternary
conditional expression offers a concise way to assign values
based on simple conditions.

To write robust and maintainable code, be cautious with floating-


point comparisons and use the "in" and "not in" operators for
collections. Utilize conditional statements in list comprehensions
and string formatting for filtering and formatting purposes.
Additionally, following best practices for writing readable code
will enhance your code's clarity and maintainability. Practice with
real-world examples will help solidify your understanding of
conditional statements, enabling you to write more efficient and
effective Python programs.

19 | P a g e
Introduction to Loops in Python

In Python, loops are a fundamental control structure that allow


a block of code to be repeatedly executed. Loops are typically
used when a set of instructions needs to be repeated either a
fixed number of times or until a particular condition is met. In
Python, we have two types of loops: the for loop and the while
loop.

Concept of Looping/Iteration

Iteration, or looping, is a concept that stands at the heart of


programming. A loop will execute a block of code repeatedly
under a specific condition. When programming, you often need
to perform a similar action on all items in a certain set of data
types, or perform the same chunk of code many times. Loops
provide a way to perform these tasks efficiently.

In essence, a loop allows code to be executed multiple times.


This could include running a block of code 10 times, iterating
over each character in a string, or repeating a set of
instructions until a certain condition is met.

The While Loop

The while loop in Python is used to repeatedly execute a block


of code as long as a given boolean condition evaluates to true.
Once the condition becomes false, the while loop stops
executing. Here is a simple example:

counter = 0

20 | P a g e
while counter < 5:

print(f"The counter is currently: {counter}")

counter += 1

In this example, the condition is counter < 5. Initially, counter


is 0. After each iteration of the loop, the counter increases by 1
(counter += 1). The loop will continue to print the statement
and increment the counter as long as the counter is less than
5.

The For Loop

The for loop in Python is used to iterate over sequences such


as lists, tuples, and strings, or other iterable objects.

Here is a simple example of using a for loop to iterate over a


list:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:

print(fruit)

In this example, fruit is the loop variable that takes on each


value in the list fruits. For each iteration, the value of fruit
changes to the next value in the fruits list, and the print
statement is executed.

Break and Continue

Sometimes, you might want to interrupt a loop's execution


before it has run its course. Python provides two keywords for
this: break and continue.

The break keyword allows you to exit the loop prematurely.


When Python encounters a break statement, it immediately
terminates the innermost loop it is in.

21 | P a g e
The continue keyword works a bit differently. Instead of
terminating the loop, it immediately jumps to the next
iteration, skipping the rest of the code inside the loop for the
current iteration.

Here is an example that demonstrates break:

for number in range(10):

if number == 5:

break

print(number)

In this example, the loop will print the numbers 0 through 4.


When the number 5 is encountered, the break statement is
executed and the loop terminates. The numbers 5 through 9
are not printed.

Now, here is an example that demonstrates continue:

for number in range(10):

if number == 5:

continue

print(number)

In this example, the loop will print the numbers 0 through 4,


skip the number 5 due to the continue statement, and then
print the numbers 6 through 9.

As you explore Python programming, you will find that loops


and iteration form the backbone of many of your scripts.
Whether you are manipulating data, creating new variables, or
setting up conditions for your program, loops offer a flexible
and efficient way to control how your code is executed.

22 | P a g e
Understanding the While loop

While Loop

In Python, the while loop repeatedly executes a block of


statements as long as a given condition is true. The condition is
checked before each execution of the loop's body.

Understanding the While Loop

Here is the basic syntax of a while loop:

while condition:

# statements

Here, condition is a boolean expression that the loop checks


before each iteration. If condition is true, the loop executes the
block of statements and then checks the condition again. This
continues until the condition becomes false.

Here is an example:

i=0

while i < 5:

print(i)

i += 1

In this example, the condition is i < 5. The print statement and


the incrementing of i are executed repeatedly while i is less
than 5. When i is no longer less than 5, the loop stops.

Infinite Loop and How to Avoid It

An infinite loop occurs when the condition of the loop never


becomes false. This results in the loop executing indefinitely.
For example:

i=0

while i < 5:
23 | P a g e
print(i)

# i is not incremented here

In this case, i never changes, so i < 5 is always true, causing


the loop to execute indefinitely. To avoid infinite loops, ensure
that the loop's condition will eventually become false.

You can use a break statement to forcefully exit the loop. Here
is an example:

i=0

while i < 5:

print(i)

if i == 3:

break

i += 1

In this example, the break statement will terminate the loop


when i equals 3.

Using else with While Loop

The else clause in a while loop specifies a block of code that


should be executed when the loop's condition becomes false.
Here is an example:

i=0

while i < 5:

print(i)

i += 1

else:

print("Loop has ended, i is now 5")

24 | P a g e
In this example, the else block executes when i is no longer
less than 5.

Note: If the loop is terminated by a break statement, the else


clause won't be executed.

Break, Continue, and Pass Statements in While Loop

These statements provide additional control over the flow of


your while loops:

The break statement can be used to terminate the loop


prematurely. When encountered, the program will immediately
exit the loop's body.

The continue statement can be used to skip the rest of the


current iteration and immediately start the next iteration.

The pass statement is a placeholder that does nothing. It's


useful when you need to write a loop that doesn't do anything
yet, but you want it to do something in the future.

Here are examples of each:

# Break example

i=0

while i < 5:

if i == 3:

break

print(i)

i += 1

# This will print 0, 1, and 2. Then the loop is terminated when i


equals 3.

# Continue example

i=0
25 | P a g e
while i < 5:

i += 1

if i == 3:

continue

print(i)

# This will print 1, 2, 4, and 5. When i equals 3, the print


statement is skipped.

# Pass example

while False:

pass

# This is an empty loop that will do nothing if executed.

In conclusion, the while loop in Python is a powerful tool that


allows you to repeat a block of code as long as a certain
condition is true. It's important to understand how to control
your loops to avoid infinite loops and to leverage break,
continue, and pass statements effectively. With practice, these
tools will become a fundamental part of your programming skill
set.

Understanding the For loop

Iterating over sequences (strings, lists, tuples, sets,


dictionaries)

Using else with For loop

Break, continue and pass statements in For loop

Range() function and its usage in loops

Enumerate() function in loops

26 | P a g e
For Loop

In Python, the for loop is used to iterate over elements of a


sequence (such as a list, tuple, string) or other iterable objects.

Understanding the For Loop

The for loop in Python has the following syntax:

for variable in sequence:

# statements

Here, variable is the variable that takes the value of the item
inside the sequence on each iteration. sequence is a list, string,
tuple, set, or any other iterable object.

Here's a simple example:

for num in [1, 2, 3, 4, 5]:

print(num)

In this case, the variable num takes on the value of each item
in the list [1, 2, 3, 4, 5] sequentially and the print statement is
executed for each item.

Iterating Over Sequences

You can use the for loop to iterate over sequences such as
strings, lists, tuples, sets, and dictionaries.

Strings: When iterating over a string, the variable takes the


value of each character in the string.

for char in "Hello":

print(char)

Lists and Tuples: When iterating over a list or tuple, the


variable takes on the value of each item in the list or tuple.

27 | P a g e
for num in [1, 2, 3, 4, 5]: # Works the same way for tuples

print(num)

Sets: When iterating over a set, the variable takes on the


value of each item in the set. Remember that sets are
unordered collections of unique elements.

for num in {1, 2, 3, 1, 2}: # Duplicates will be removed

print(num)

Dictionaries: When iterating over a dictionary, the variable


takes on the value of each key. To iterate over values or key-
value pairs, you can use .values() and .items(), respectively.

dict_example = {"one": 1, "two": 2, "three": 3}

for key in dict_example:

print(key) # Prints the keys

for value in dict_example.values():

print(value) # Prints the values

for key, value in dict_example.items():

print(key, value) # Prints keys and values

Using else with For Loop

The else clause in a for loop specifies a block of code to be


executed when the loop has finished, i.e., when the items in
the sequence have been completely iterated over.

Here's an example:

for num in [1, 2, 3, 4, 5]:

print(num)

else:

print("The loop has ended")


28 | P a g e
Note: The else clause won't be executed if the loop is
prematurely stopped by a break statement.

Break, Continue, and Pass Statements in For Loop

The break statement allows you to exit the loop prematurely.


When encountered, the loop is immediately terminated.

for num in [1, 2, 3, 4, 5]:

if num == 3:

break

print(num)

# This will print 1 and 2, then stop when it encounters 3.

The continue statement skips the rest of the current iteration


and immediately proceeds to the next iteration.

for num in [1, 2, 3, 4, 5]:

if num == 3:

continue

print(num)

# This will print 1, 2, 4, 5. It skips printing 3.

The pass statement is a placeholder that does nothing. It is


used when a statement is required for syntactic reasons, but
no action needs to be taken.

for num in [1, 2, 3, 4, 5]:

pass # This loop does nothing

Range() Function and Its Usage in Loops

The range() function is often used with loops to generate


sequences of numbers. It can be used with one, two, or three
arguments. Here are examples of each:

29 | P a g e
One argument: generates numbers from 0 to the argument
minus 1.

for i in range(5):

print(i)

# This will print 0, 1, 2, 3, 4.

Two arguments: generates numbers from the first argument to


the second argument minus 1.

for i in range(1, 5):

print(i)

# This will print 1, 2, 3, 4.

Three arguments: the third argument specifies the step, i.e.,


the difference between each number in the sequence.

for i in range(1, 10, 2):

print(i)

# This will print 1, 3, 5, 7, 9.

Enumerate() Function in Loops

The enumerate() function can be used to generate an index


along with the value during a loop. Here's an example:

for i, num in enumerate([10, 20, 30, 40, 50]):

print(f"Index: {i}, Value: {num}")

# This will print the index and value for each item in the
list.

In this example, i is the index and num is the value for each
item in the list. The enumerate() function makes it easy to get
both the index and the value in the same loop, which can be
very helpful in many situations.

30 | P a g e
Remember that for loops in Python are a powerful tool to
iterate over sequences and other iterable objects. By
understanding how to use for loops effectively, you can write
more efficient and cleaner code.

Nested Loops

In Python, we can use loops inside loops, which are called


nested loops. A nested loop is a loop that occurs within another
loop, structurally similar to nested if statements. The "inner
loop" will be finished before the next iteration of the "outer
loop" starts.

Understanding Nested Loops

Here's the basic syntax of a nested loop in Python:

for outer_variable in outer_sequence:

# outer loop body

for inner_variable in inner_sequence:

# inner loop body

# rest of outer loop body

In the example above, outer_sequence and inner_sequence


could be any iterable objects, such as lists, strings, tuples, etc.
The inner loop will finish all of its iterations for each single
iteration of the outer loop.

Nested For Loop Example

Here is an example of a nested loop where we have a list of


lists:

nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

for outer_list in nested_list:

31 | P a g e
for item in outer_list:

print(item, end=' ')

print()

This will output:

123

456

789

In this example, for each iteration of the outer loop, the inner
loop runs completely. The end=' ' in the print statement is used
to print on the same line, and the print() statement without
any arguments is used to print a newline.

Nested While Loop Example

Here's an example with a while loop inside a for loop:

for i in range(1, 4):

j=1

while j <= 3:

print(f"i = {i}, j = {j}")

j += 1

This will output:

i = 1, j = 1

i = 1, j = 2

i = 1, j = 3

i = 2, j = 1

i = 2, j = 2

i = 2, j = 3
32 | P a g e
i = 3, j = 1

i = 3, j = 2

i = 3, j = 3

In this example, the inner while loop executes 3 times for each
single execution of the outer for loop.

Exercises

Create a nested loop that prints the multiplication table from 1


to 10.

for i in range(1, 11):

for j in range(1, 11):

print(i * j, end='\t')

print() # to start a new line for each i

Create a nested loop that generates a pyramid of stars. For


example, a pyramid of height 5 would look like this:

***

*****

*******

*********

height = 5

for i in range(height):

# print spaces

for j in range(height - i - 1):

print(" ", end="")

# print stars
33 | P a g e
for j in range(2 * i + 1):

print("*", end="")

print() # to start a new line for each i

The concept of nested loops can initially seem complex, but


with practice, it becomes a powerful tool for solving more
complex problems. Always remember that each inner loop will
run to completion for each iteration of its outer loop. Happy
coding!

Basics of list comprehension

List Comprehension

List comprehension is a succinct and efficient way to create


lists in Python. It allows you to create lists using a single line of
code.

Basics of List Comprehension

The basic syntax of list comprehension is:

[expression for item in iterable]

For example, you can create a list of the squares of numbers


from 1 to 5 like this:

squares = [x**2 for x in range(1, 6)]

print(squares) # Prints: [1, 4, 9, 16, 25]

In the example above, x**2 is the expression that is computed


for each item in the iterable range(1, 6).

Advantages Over Traditional Loops

List comprehensions are more compact and faster than


traditional loops for creating lists.

Compare these two pieces of code that do the same thing:

34 | P a g e
Using a for loop:

squares = []

for x in range(1, 6):

squares.append(x**2)

print(squares) # Prints: [1, 4, 9, 16, 25]

Using list comprehension:

squares = [x**2 for x in range(1, 6)]

print(squares) # Prints: [1, 4, 9, 16, 25]

As you can see, the list comprehension version is shorter and


easier to read. It's also faster because appending to a list is an
expensive operation, and list comprehensions are optimized in
Python to avoid this cost.

Conditions in List Comprehension

You can also include an if condition in a list comprehension to


filter items from the iterable. The syntax is as follows:

[expression for item in iterable if condition]

For example, you can create a list of the squares of numbers


from 1 to 5, but only for the even numbers:

squares = [x**2 for x in range(1, 6) if x % 2 == 0]

print(squares) # Prints: [4, 16]

In this case, x % 2 == 0 is the condition that filters the items


from the iterable.

35 | P a g e
Nested List Comprehension

You can also use list comprehension inside another list


comprehension, which is known as a nested list
comprehension.

For example, you can create a matrix (list of lists) of numbers


like this:

matrix = [[i for i in range(j, j+3)] for j in range(1, 4)]

print(matrix) # Prints: [[1, 2, 3], [2, 3, 4], [3, 4, 5]]

In the example above, the outer list comprehension [i for i in


range(j, j+3)] creates a list of numbers for each value of j in
the range from 1 to 3.

List comprehensions are a powerful tool in Python, allowing you


to write more compact and faster code. They can take a while
to get used to, especially when conditions or nested list
comprehensions are involved, but once you get the hang of
them, you'll find them invaluable.

Loop Control Statements

Loop control statements change the execution from its normal


sequence. In Python, we have three types of control
statements: break, continue, and pass.

Break Statement

The break statement is used to terminate the loop prematurely


when a certain condition is met. When a break statement is
encountered inside a loop, the control directly comes out of the
loop, and the loop gets terminated for the rest of the iterations.

36 | P a g e
Example:

for num in range(10):

if num == 5:
break
print(num)

In this example, the loop will print the numbers from 0 to 4.


When the loop variable num is 5, the break statement is
executed and the loop is terminated.

Continue Statement

The continue statement is used to skip the rest of the code


inside the loop for the current iteration only. The loop does not
terminate but continues on with the next iteration.

Example:

for num in range(10):

if num == 5:

continue

print(num)

In this example, the loop will print all the numbers except 5.
When the loop variable num is 5, the continue statement is
executed, and the current iteration is skipped, but the loop
continues with the next iteration.

Pass Statement

Pass is a placeholder statement. It is used when a statement is


required syntactically, but you do not want any command or
code to execute. The pass statement is a null operation;
nothing happens when it executes.

37 | P a g e
Example:

for num in range(10):

if num == 5:

pass

print(num)

In this case, pass does nothing and the number 5 is printed like
all the other numbers. The pass statement is also useful in
places where your code will eventually go, but has not been
written yet (e.g., in stub functions or loops).

Understanding these loop control statements can make your


coding in Python more efficient and logical. You can use break
and continue in your loops to add or skip functionality based on
specific conditions, and pass can be used as a placeholder
when you're sketching out the structure of your program.

38 | P a g e

You might also like