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
Practice Exercises for Day 4

Exercise 1: Voting Eligibility

Write a Python program that takes the age of a person as input and checks whether the person is eligible to vote or not. (Age should be 18 or above to be eligible.)


Exercise 2: Grading System
Write a Python program that takes the marks of a student as input and prints the grade based on the following criteria:
Marks >= 90: Grade A
Marks >= 80: Grade B
Marks >= 70: Grade C
Marks >= 60: Grade D
Marks < 60: Grade F


Exercise 3: Leap Year Checker
Write a Python program to check if a given year is a leap year or not. A leap year is exactly divisible by 4, except for years that are exactly divisible by 100. However, years divisible by 400 are leap years.


Exercise 4: Odd or Even
Write a Python program that takes a number as input and checks whether the number is odd or even.


Exercise 5: Calculator Using if-elif-else
Create a simple calculator that takes two numbers and an operator (+, -, *, /) as input and performs the corresponding operation using if-elif-else statements.
👍1
Homework for Day 4

BMI Calculator:

Write a Python program that takes the weight (in kg) and height (in meters) of a person as input and calculates their Body Mass Index (BMI). The program should then categorize the BMI as:
BMI < 18.5: Underweight
18.5 <= BMI < 24.9: Normal weight
25 <= BMI < 29.9: Overweight
BMI >= 30: Obesity


Number Classification:
Write a Python program that takes an integer as input and checks if it is positive, negative, or zero

Password Strength Checker:
Create a Python program that takes a password as input and checks its strength based on the following criteria:
At least 8 characters long
Contains both uppercase and lowercase characters
Contains at least one digit
Contains at least one special character (e.g., @, #, !)


Nested if Example:
Write a Python program that takes a person's age and income as input and prints whether the person has to pay taxes. The tax rules are:
If the age is less than 18, they do not need to pay taxes.
If the age is between 18 and 60, they need to pay taxes if their income is more than 5 lakh.
If the age is above 60, they need to pay taxes if their income is more than 3 lakh.
👍3
Summary

Today, we covered conditional statements in Python, which are crucial for controlling the flow of a program. We learned about:

if, elif, and else statements: Used for decision-making in Python.
Nested if statements: Allow for more complex decision-making processes.
Combining conditions using logical operators (and, or, not) to create complex expressions.
Conditional expressions (ternary operators): A concise way to write if...else statements.

Understanding and mastering these concepts will help you write programs that can make decisions based on user input or other factors, making your code more dynamic and responsive.
👍4
Which keyword is used to check a condition in Python?
Anonymous Quiz
8%
for
77%
if
8%
while
6%
switch
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 loop
for loop

Both loops are used to perform repetitive tasks but have different use cases and syntax.
👍2
The while Loop
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
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
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 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]