Free Python Course | Programming Tutorials
599 subscribers
9 photos
2 files
6 links
Join Noob to Pro in Python in 100 Days! 🚀 Learn Python with daily lessons, practical examples, free code samples, exercises, and homework. Ideal for beginners and those looking to advance their skills. Start your journey to becoming a Python pro! 🐍
Download Telegram
The range() Function
The 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
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:

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 else with Loops
In 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
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:

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:

- 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
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
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.
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
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
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
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
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:
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
Converting Between Lists and Tuples
You can convert a list to a tuple and vice versa using list() and tuple() functions.

Examples:
# List to Tuple
list1 = [1, 2, 3]
tuple1 = tuple(list1)
print(tuple1) # Output: (1, 2, 3)

# Tuple to List
tuple2 = (4, 5, 6)
list2 = list(tuple2)
print(list2) # Output: [4, 5, 6]
Unpacking Lists and Tuples
You can "unpack" a list or tuple into individual variables.

Example:
point = (1, 2, 3)
x, y, z = point
print(x, y, z) # Output: 1 2 3
Practice Exercises for Day 6

Exercise 1: List Operations

Create a list of 5 numbers. Perform the following operations: append a new number, remove the second element, and sort the list.


Exercise 2: Find the Largest Number in a List
Write a Python program that finds the largest number in a list without using built-in functions.


Exercise 3: Tuple Packing and Unpacking
Write a Python program that packs four values into a tuple and then unpacks them into separate variables.


Exercise 4: List Comprehensions
Write a Python program that creates a new list with the squares of numbers from 1 to 10 using list comprehensions.


Exercise 5: Matrix Operations
Create a 3x3 matrix using nested lists. Write a Python program to print the matrix and its transpose.
Homework for Day 6

Create a Shopping Cart Program:

Create a Python program that allows the user to add items to a shopping cart. Use a list to store the items, and provide options to add, remove, view, and clear the cart.


Tuple-Based Menu:
Write a program that displays a tuple-based menu to the user. The menu should contain options for various operations (e.g., add, delete, view items) and perform actions based on user input.


Flatten a Nested List:
Write a Python program to flatten a nested list using list comprehensions.


Unique Elements Finder:
Create a Python program that takes a list of numbers and returns a new list containing only the unique elements (removing duplicates).


Tuple Manipulation:
Write a Python program to take a tuple of numbers and return a tuple containing only even numbers.
Summary
Today, we covered two of Python's fundamental data structures: Lists and Tuples. We learned:

Lists are mutable and allow for dynamic operations like adding, removing, and sorting elements.
Tuples are immutable, making them suitable for fixed collections of items.
List methods help manipulate lists efficiently.
Tuple methods provide limited but useful operations for tuple manipulation.
List comprehensions offer a concise way to create new lists.
Nested lists and unpacking are useful techniques for handling complex data.

These data structures are foundational for Python programming, and mastering them will help you manage and manipulate data effectively in your projects. Keep practicing and experimenting with these concepts to strengthen your Python skills. Happy coding!