Which of the following operators can be used to combine multiple conditions in Python?
Anonymous Quiz
31%
&& and ||
26%
AND and OR
40%
and and or
2%
AND and ||
Introduction to Loops
Loops allow you to execute a block of code multiple times. Python provides two types of loops:
while loopfor loopBoth loops are used to perform repetitive tasks but have different use cases and syntax.
👍2
The while Loop
Syntax
Example
In this example, the loop runs until the value of
The while loop executes a block of code as long as the given condition is True. It is primarily used when the number of iterations is not known beforehand.
Syntax
while condition:
# Code to execute repeatedly as long as the condition is True
Example
count = 0
while count < 5:
print("Count is:", count)
count += 1 # Increment count by 1
In this example, the loop runs until the value of
count becomes 5. The count += 1 statement increments the value of count by 1 in each iteration.Infinite while Loop
Example of an Infinite Loop:
You can stop an infinite loop by using
A while loop can become an infinite loop if the condition never becomes False. You need to be careful to include a condition that will eventually break the loop.
Example of an Infinite Loop:
while True:
print("This will run forever if not stopped!")
You can stop an infinite loop by using
break or by manually interrupting the program (e.g., pressing Ctrl + C).The for Loop
Syntax
Example
Here, the
The for loop is used to iterate over a sequence (like a list, tuple, string, or range). It is most commonly used when the number of iterations is known beforehand.
Syntax
for variable in sequence:
# Code to execute for each element in the sequence
Example
for i in range(5):
print("Value of i:", i)
Here, the
range(5) function generates a sequence of numbers from 0 to 4, and the loop runs 5 times.The
The range() function is widely used in
Example:
range() FunctionThe range() function is widely used in
for loops to generate a sequence of numbers. It has three parameters:range(stop) - Generates numbers from 0 to stop - 1.range(start, stop) - Generates numbers from start to stop - 1.range(start, stop, step) - Generates numbers from start to stop - 1 with a step size of step.Example:
print(list(range(5))) # Output: [0, 1, 2, 3, 4]
print(list(range(2, 7))) # Output: [2, 3, 4, 5, 6]
print(list(range(1, 10, 2))) # Output: [1, 3, 5, 7, 9]
Nested Loops
Example:
Output:
A loop inside another loop is called a nested loop. The inner loop runs completely whenever the outer loop runs once.
Example:
for i in range(1, 4):
for j in range(1, 4):
print(f"i={i}, j={j}")
Output:
i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
...
Loop Control Statements
Python provides loop control statements to change the execution flow of loops:
Python provides loop control statements to change the execution flow of loops:
break statement: Terminates the loop prematurely.continue statement: Skips the current iteration and continues with the next iteration.pass statement: Does nothing and can be used as a placeholder.break Example:for i in range(5):
if i == 3:
break
print(i)
# Output: 0 1 2
continue Example:for i in range(5):
if i == 3:
continue
print(i)
# Output: 0 1 2 4
pass Example: for i in range(5):
if i == 3:
pass # Placeholder, does nothing
print(i)
# Output: 0 1 2 3 4
Using
In Python, you can use an
Example with
Example with
else with LoopsIn Python, you can use an
else block with both while and for loops. The else block is executed when the loop terminates normally (i.e., not terminated by a break statement).Example with
for loop: for i in range(5):
print(i)
else:
print("Loop completed successfully.")
Example with
while loop:count = 0
while count < 5:
print(count)
count += 1
else:
print("Loop completed successfully.")
Practice Exercises for Day 5
Exercise 1: Sum of First N Natural Numbers
Exercise 2: Multiplication Table
Exercise 3: List Iteration
Exercise 4: Factorial Calculation
Exercise 5: Prime Number Checker
Exercise 1: Sum of First N Natural Numbers
Write a Python program to find the sum of the first N natural numbers using a while loop.
Exercise 2: Multiplication Table
Write a Python program to print the multiplication table of a given number using a for loop.
Exercise 3: List Iteration
Given a list of numbers, write a Python program to print each number in the list using a for loop.
Exercise 4: Factorial Calculation
Write a Python program to calculate the factorial of a number using a while loop.
Exercise 5: Prime Number Checker
Write a Python program that takes an integer as input and checks whether it is a prime number or not using a for loop.
Homework for Day 5
Pattern Printing:
Fibonacci Sequence Generator:
Even and Odd Counter:
.
Guess the Number Game (Enhanced):
Nested Loop Practice:
Pattern Printing:
Write a Python program to print the following pattern using nested loops:
*
* *
* * *
* * * *
* * * * *
Fibonacci Sequence Generator:
Write a Python program to generate the first N Fibonacci numbers using a while loop.
Even and Odd Counter:
Write a Python program that takes a list of numbers and counts the number of even and odd numbers using a for loop and if condition
.
Guess the Number Game (Enhanced):
Enhance the "Guess the Number" game (from previous days) to provide a limited number of attempts (e.g., 5 attempts). After each wrong guess, inform the user of the remaining attempts.
Nested Loop Practice:
Write a Python program that takes an input number n and prints an n x n multiplication table using nested loops
Summary
Today, we covered loops in Python, a fundamental concept for automating repetitive tasks:
-
-
- Loop control statements (
- Nested loops are used for complex iterations within iterations.
Today, we covered loops in Python, a fundamental concept for automating repetitive tasks:
-
while loops are used when the number of iterations is not known beforehand.-
for loops are used to iterate over a sequence and are most useful when the number of iterations is known.- Loop control statements (
break, continue, pass) help modify the flow of loops.- Nested loops are used for complex iterations within iterations.
Introduction to Lists
Syntax:
Example:
A list is a versatile, ordered collection in Python that can store a sequence of items. Lists are mutable, meaning their contents can be changed after they are created.
Syntax:
my_list = [item1, item2, item3, ...]
Example:
fruits = ["apple", "banana", "cherry"]
print(fruits) # Output: ['apple', 'banana', 'cherry']
🥰1
List Indexing and Slicing
Example:
Example:
Indexing: Access individual elements in a list using their index (starting from 0).
Example:
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple
Slicing: Access a subset of elements using a range of indices.
Example:
print(fruits[0:2]) # Output: ['apple', 'banana']
Common List Methods
Lists come with several built-in methods to perform common operationsappend(item): Adds an item to the end of the list.
Example:
Lists come with several built-in methods to perform common operationsappend(item): Adds an item to the end of the list.
insert(index, item): Inserts an item at a specified index.remove(item): Removes the first occurrence of an item.pop(index): Removes and returns the item at the specified index. If no index is provided, it removes the last item.sort(): Sorts the list in ascending order.reverse(): Reverses the order of the list.index(item): Returns the index of the first occurrence of an item.count(item): Returns the number of times an item appears in the list.clear(): Removes all elements from the list.Example:
numbers = [3, 1, 4, 1, 5, 9]
numbers.append(2)
print(numbers) # Output: [3, 1, 4, 1, 5, 9, 2]
numbers.sort()
print(numbers) # Output: [1, 1, 2, 3, 4, 5, 9]
numbers.pop()
print(numbers) # Output: [1, 1, 2, 3, 4, 5]
List Comprehensions
Syntax:
Example:
List comprehensions provide a concise way to create lists. It can be used to apply an expression to each item in an iterable.
Syntax:
new_list = [expression for item in iterable if condition]
Example:
squares = [x**2 for x in range(10)]
print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Nested Lists
Example:
A nested list is a list that contains another list as its element.
Example:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[1]) # Output: [4, 5, 6]
print(matrix[1][1]) # Output: 5
Introduction to Tuples
Syntax:
Example:
A tuple is similar to a list but is immutable, meaning it cannot be modified after creation. Tuples are used for fixed collections of items.
Syntax:
my_tuple = (item1, item2, item3, ...)
Example:
colors = ("red", "green", "blue")
print(colors) # Output: ('red', 'green', 'blue')Accessing Tuple Elements
Example:
Like lists, tuples can be indexed and sliced.
Example:
print(colors[0]) # Output: red
print(colors[0:2]) # Output: ('red', 'green')
Tuple Methods
Tuples have fewer built-in methods compared to lists since they are immutable:
Example:
Tuples have fewer built-in methods compared to lists since they are immutable:
count(item): Returns the number of times an item appears in the tuple.index(item): Returns the index of the first occurrence of an item.Example:
t = (1, 2, 3, 1, 2)
print(t.count(1)) # Output: 2
print(t.index(3)) # Output: 2
👍1