[go: up one dir, main page]

0% found this document useful (0 votes)
36 views41 pages

Untitled Document

The document outlines a series of Python coding challenges covering various topics such as conditionals, loops, functions, recursion, lambda functions, list comprehensions, error handling, and a mini project for a CLI To-Do List app. Each section includes explanations, code examples, and mini projects to practice the concepts. The document aims to enhance Python programming skills through practical applications and exercises.

Uploaded by

rohaile278
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)
36 views41 pages

Untitled Document

The document outlines a series of Python coding challenges covering various topics such as conditionals, loops, functions, recursion, lambda functions, list comprehensions, error handling, and a mini project for a CLI To-Do List app. Each section includes explanations, code examples, and mini projects to practice the concepts. The document aims to enhance Python programming skills through practical applications and exercises.

Uploaded by

rohaile278
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/ 41

Today, Let’s move on to the next topic in the Python Coding Challenge:

🔹 *Day 6: Conditionals (if, elif, else)*


In Python, conditional statements allow your code to make decisions.

💡 *What Are Conditionals?*


They help your program execute certain code blocks only when specific conditions are true.

✅ *Syntax* :
if condition:
# Code runs if condition is True
elif another_condition:
# Runs if previous conditions were False, this one is True
else:
# Runs if none of the above conditions are True

🧠 *Example* :
age = 18

if age >= 18:


print("You’re an adult.")
elif age > 13:
print("You’re a teenager.")
else:
print("You’re a child.")

*Output:*

You’re an adult.

🎯 *Mini Project: Guess the Number Game*


Let’s build a small game using what we’ve learned so far:

*Python Code*

import random

number = random.randint(1, 10)


guess = int(input("Guess a number between 1 and 10: "))

🎉
if guess == number:
print(" Correct! You guessed it right.")
elif guess < number:
print("Too low! Try again.")
else:
print("Too high! Try again.")

print(f"The correct number was: {number}")

This project uses:

- if, elif, else


- User input
- Random module

*React with ❤️ once you’re ready for the quiz*


Python Coding Challenge:
https://whatsapp.com/channel/0029VaiM08SDuMRaGKd9Wv0L/1661

Today, Let’s move on to the next topic in the Python Coding Challenge:

🔹 *Day 7: Loops in Python (for and while)*


Loops are one of the most powerful tools in programming. They help us repeat tasks without
writing repetitive code.

🔁 *for Loop*
Use a for loop when you know how many times you want to repeat something.

```for i in range(5):
print(i)```

🟢 *Output* :
0
1
2
3
4

✅ range(5) creates a sequence from 0 to 4


✅ i takes each value one by one
🔁 *while Loop*
Use a while loop when you want to repeat until a condition is no longer true.

```count = 1
while count <= 5:
print(count)
count += 1```

🟢 *Output* :
1
2
3
4
5

🔨 *Mini Projects to Practice*


*1. Multiplication Table Generator*

```num = int(input("Enter a number: "))

for i in range(1, 11):


print(f"{num} x {i} = {num * i}")```

👉 *This lets users generate the multiplication table of any number.*


*2. Pattern Printer (Staircase of Stars)*

```rows = 5
for i in range(1, rows + 1):
print("*" * i)```

🟢 *Output:*
*
**
***
****
*****

👉 *Great intro to nested logic and string multiplication.*


*React with ❤️ once you’re ready for the quiz*

Python Coding Challenge:


https://whatsapp.com/channel/0029VaiM08SDuMRaGKd9Wv0L/1661
Today, Let’s move on to the next topic in the Python Coding Challenge:

🔹 *Day 8: Functions in Python*


🤔 *What is a Function?*
A function is a reusable block of code that performs a specific task.

Think of it as a machine: you give it some input (arguments), it processes something, and then
gives you output.

✅ *Defining a Function*
Here’s the basic structure:

def greet():
print("Hello, Python learner!")

To call or run the function:

greet()

🟢 *Output:*
Hello, Python learner!

✅ *Function with Parameters*


You can make your function accept values using parameters:

def greet(name):
print(f"Hello, {name}!")

greet("Sam")

🟢 *Output:*
Hello, Sam!

✅ *Return Values*
Functions can return values instead of just printing them:

def add(a, b):


return a + b

result = add(3, 5)
print(result)

🟢 *Output:* 8
🔨 *Mini Project: Prime Number Checker*
Let’s use what we learned to create a small, useful function!

def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True

# Try it!
num = int(input("Enter a number: "))
if is_prime(num):
print("It's a prime number.")
else:
print("Not a prime number.")

🧠 *This project introduces:*


- Logic inside a function
- Conditional checks

- Looping through a range

*React with ❤️ once you’re ready for the quiz*


Python Coding Challenge:
https://whatsapp.com/channel/0029VaiM08SDuMRaGKd9Wv0L/1661
Today, Let’s move on to the next topic in the Python Coding Challenge:

🔹 *Day 9: Function Arguments in Python*


🤔 *Why are Arguments Important?*
Arguments allow us to pass data into a function so it can act on different values — making the
function dynamic instead of static.

✅ *Types of Function Arguments*


*1. Positional Arguments*

These are the most common — the order matters.

```def greet(name, age):


print(f"{name} is {age} years old.")

greet("Alex", 25) ```

*2. Keyword Arguments*

You specify the name of the argument, so order doesn’t matter.

greet(age=25, name="Alex")

*3. Default Arguments*

Provide a default value so the argument becomes optional.

```def greet(name, city="Delhi"):


print(f"{name} is from {city}")
greet("Riya") # Uses default city
greet("Riya", "Mumbai") # Overrides default

```

*4. Variable-length Arguments*

*args for multiple positional values (tuple)

**kwargs for multiple keyword values (dictionary)

```
def total(*numbers):
return sum(numbers)

print(total(2, 4, 6)) # Outputs: 12

def display_info(**data):
for key, value in data.items():
print(f"{key} = {value}")

display_info(name="John", age=30)
```

🔨 *Mini Project: Tip Calculator with Tax*


```
def calculate_total(bill, tip_percent=10, tax_percent=5):
tip = bill * (tip_percent / 100)
tax = bill * (tax_percent / 100)
return bill + tip + tax

amount = float(input("Enter bill amount: "))


total_amount = calculate_total(amount, tip_percent=15)
print(f"Total Amount to Pay: ₹{total_amount:.2f}")
```

🧠 This project demonstrates:


- Positional and default arguments

- Mathematical logic
- Function flexibility

*React with ❤️ once you’re ready for the quiz*


Python Coding Challenge:
https://whatsapp.com/channel/0029VaiM08SDuMRaGKd9Wv0L/1661

Today, Let’s move on to the next topic in the Python Coding Challenge:

🔹 *Day 10: Recursion Basics*


🤔 *What is Recursion?*
Recursion is when a function calls itself to solve smaller parts of a problem — ideal for tasks
that can be broken down into repetitive subproblems.

✅ *Basic Recursive Structure*


def function_name():
# base condition
if condition:
return something
else:
return function_name() # recursive call

Without a base condition, the function will keep calling itself forever — causing a
RecursionError.

💡 *Example 1: Factorial Using Recursion*


def factorial(n):
if n == 0 or n == 1: # base case
return 1
else:
return n * factorial(n - 1)

print(factorial(5)) # Output: 120

*Here’s how it works:*

factorial(5)
→ 5 * factorial(4)
→ 5 * 4 * factorial(3)
→ 5 * 4 * 3 * factorial(2)
→ ...
→ 5 * 4 * 3 * 2 * 1 = 120

💡 *Example 2: Fibonacci Series Using Recursion*


def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)

for i in range(7):
print(fibonacci(i), end=' ') # Output: 0 1 1 2 3 5 8

🔨 *Mini Project:*
*Factorial & Fibonacci Calculator*

def factorial(n):
return 1 if n <= 1 else n * factorial(n - 1)

def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)

num = int(input("Enter a number: "))


print("Factorial:", factorial(num))
print("Fibonacci:", fibonacci(num))

This covers:

- Recursive thinking
- Base vs. recursive case
- Classic math problems

*React with ❤️ once you’re ready for the quiz*


Python Coding Challenge:
https://whatsapp.com/channel/0029VaiM08SDuMRaGKd9Wv0L/1661

Today, Let’s move on to the next topic in the Python Coding Challenge: ⚡🐍
🔹 *Day 11: Lambda, map(), and filter()*
🧠 *What is a Lambda Function?*
A lambda function is an anonymous function written in one line using the lambda keyword.

✅ *Syntax:*
lambda arguments: expression

🔸 *Example:*
square = lambda x: x ** 2
print(square(5)) # Output: 25

> 🔹 Use lambdas when you need a simple function for a short time — usually as an argument
to map(), filter(), or sorted().

🧩 *map() — Apply a Function to All Items*


Takes a function and an iterable, and applies the function to every item in the iterable.

nums = [1, 2, 3, 4]
squares = list(map(lambda x: x ** 2, nums))
print(squares) # Output: [1, 4, 9, 16]

🧼 *filter() — Filter Items Based on a Condition*


Filters the iterable by applying a function that returns True/False.

nums = [1, 2, 3, 4, 5, 6]
even = list(filter(lambda x: x % 2 == 0, nums))
print(even) # Output: [2, 4, 6]

🔨 *Mini Project: Filter & Transform List*


nums = list(range(1, 21))

# Step 1: Keep only even numbers


even_nums = list(filter(lambda x: x % 2 == 0, nums))

# Step 2: Square the even numbers


squared_evens = list(map(lambda x: x ** 2, even_nums))

print("Even numbers:", even_nums)


print("Squared evens:", squared_evens)

You just combined filtering and transformation using lambda, map, and filter!

*React with ❤️ once you’re ready for the quiz*


Python Coding Challenge:

⚡🐍
https://whatsapp.com/channel/0029VaiM08SDuMRaGKd9Wv0L/1661
Today, Let’s move on to the next topic in the Python Coding Challenge:

🔹 *Day 12: List Comprehensions in Python*


A list comprehension is a concise way to create lists by applying an expression to each item in
an iterable.

✅ *Basic Syntax* :
[expression for item in iterable if condition]

🔸 *Example 1: Square All Numbers*


nums = [1, 2, 3, 4]
squares = [x**2 for x in nums]
print(squares) # Output: [1, 4, 9, 16]

🔸 *Example 2: Filter Even Numbers*


nums = [1, 2, 3, 4, 5, 6]
evens = [x for x in nums if x % 2 == 0]
print(evens) # Output: [2, 4, 6]

🔸 *Example 3: Convert Strings to Uppercase*


names = ["alice", "bob", "charlie"]
upper_names = [name.upper() for name in names]
print(upper_names) # Output: ['ALICE', 'BOB', 'CHARLIE']

🔁 *Equivalent Using Loops:*


squares = []
for x in nums:
squares.append(x**2)

List comprehensions are faster, cleaner, and more readable when used correctly.

🔨 *Mini Project: Filter Odd Numbers and Cube Them*


```
nums = list(range(1, 11))
odd_cubed = [x**3 for x in nums if x % 2 != 0]
print("Cubes of odd numbers from 1 to 10:", odd_cubed)
```

🧠 *This shows:*
- Filtering (odds only)

- Transformation (cubing)

- Compact, readable logic

*React with ❤️ once you’re ready for the quiz*


Python Coding Challenge:
https://whatsapp.com/channel/0029VaiM08SDuMRaGKd9Wv0L/1661
⚡🐍
Today, Let’s move on to the next topic in the Python Coding Challenge:

🔹 *Day 13: Error Handling in Python*


When something unexpected happens — like dividing by zero or reading a missing file —
Python raises an exception.
If not handled, your program crashes.

✅ *The try...except Block*


try:
# risky code
except SomeError:
# handle error

🔸 *Example* :
try:
x = int(input("Enter a number: "))
print(10 / x)
except ZeroDivisionError:
print("You can't divide by zero!")
except ValueError:
print("Please enter a valid number.")

🔹 *else and finally*


else: runs if no exception was raised

finally: runs no matter what (cleanup code)

try:
num = int(input("Enter number: "))
except ValueError:
print("Not a number!")
else:
print("Square is", num ** 2)
finally:
print("Done.")
*Common Exceptions:*

- ZeroDivisionError – dividing by zero

- ValueError – invalid value (e.g., int("abc"))

- TypeError – wrong data type

- FileNotFoundError – file doesn't exist

- IndexError – index out of range

🔨 *Mini Project: Safe Input Reader*


A safe input reader is a function or piece of code that asks the user for input — but doesn’t
crash if the user types something invalid.

*Python Code*:
```
def get_integer(prompt):
try:
return int(input(prompt))
except ValueError:
print("That's not a valid integer!")
return None

num = None
while num is None:
num = get_integer("Enter an integer: ")

print("You entered:", num)


```

🔑 *This project helps:*


- Prevent program crashes

- Give user-friendly error messages

- Build real-world safety into your code


*React with ❤️ once you’re ready for the quiz*
Python Coding Challenge:
https://whatsapp.com/channel/0029VaiM08SDuMRaGKd9Wv0L/1661

Today, Let’s move on to the next topic in the Python Coding Challenge: ⚡🐍
🔹 *Day 14: Mini Project – CLI To-Do List App*
📋 You’ll use everything you've learned so far: functions, input/output, lists, and error handling.
✅ *What You'll Build:*
A simple Command-Line To-Do List where users can:

- Add tasks

- View tasks

- Remove tasks

- Exit the app safely

🛠️ *Python Code:*
```
todo_list = []

def show_menu():
print("\nTo-Do List Options:")
print("1. View Tasks")
print("2. Add Task")
print("3. Remove Task")
print("4. Exit")

def view_tasks():
if not todo_list:
print("No tasks yet!")
else:
print("\nYour Tasks:")
for idx, task in enumerate(todo_list, start=1):
print(f"{idx}. {task}")
def add_task():
task = input("Enter the task: ")
todo_list.append(task)
print("Task added!")

def remove_task():
view_tasks()
try:
index = int(input("Enter task number to remove: ")) - 1
removed = todo_list.pop(index)
print(f"Removed: {removed}")
except (ValueError, IndexError):
print("Invalid task number.")

while True:
show_menu()
choice = input("Choose an option (1-4): ")

if choice == "1":
view_tasks()
elif choice == "2":
add_task()
elif choice == "3":
remove_task()
elif choice == "4":
print("Goodbye!")
break
else:
print("Invalid option. Please choose 1–4.")
```

💡 *What You Practiced:*


- Functions & modular design

- try-except blocks for safety

- List manipulation (append, pop)

- CLI-based input/output

*React with ❤️ if you're ready for the next topic*


Python Coding Challenge:

📁📝
https://whatsapp.com/channel/0029VaiM08SDuMRaGKd9Wv0L/1661
Today, Let’s move on to the next topic in the Python Coding Challenge:

🔹 *Day 15: Reading & Writing Files in Python*


🤔 *Why Learn File Handling* ?
It allows your Python programs to:

- Save user data


- Read logs or configuration files
- Process data stored in .txt, .csv, etc.

✅ *Opening a File*
file = open("example.txt", "r") # 'r' = read mode
content = file.read()
file.close()

⚠️ *Always close the file after opening — or use the safer with keyword* .

✅ *Using "with" (Best Practice)*


with open("example.txt", "r") as file:
content = file.read()
print(content)

Using "with", the file closes automatically after use.

✍️ *Writing to a File*
with open("data.txt", "w") as file:
file.write("Hello, Python!")

- 'w' mode overwrites the file


- 'a' mode appends to the file

🔄 *Reading Line by Line*


with open("data.txt", "r") as file:
for line in file:
print(line.strip())

🔨 *Mini Project: Notes Saver*


filename = "notes.txt"

note = input("Write your note: ")

with open(filename, "a") as file:


file.write(note + "\n")

print("Note saved to", filename)

*This tiny app lets the user:*

- Write notes
- Save them in a .txt file
- Append new notes instead of overwriting

*React with ❤️ if you're ready for the next quiz*


Python Coding Challenge:
https://whatsapp.com/channel/0029VaiM08SDuMRaGKd9Wv0L/1661

Today, Let’s move on to the next topic in the Python Coding Challenge: 📁📝
🔹 *Creating & Using Custom Modules*
🤔 *What is a Module?*
A module is just a `.py` file containing functions, variables, or classes you can reuse across
other files.

✅ *Why Use Modules?*


• Reuse code
• Keep things organized
• Avoid repetition
• Easier to debug and collaborate

📁 *Example: Create a Custom Module*


🗂️ `mymath.py`
```python
def add(a, b):
return a + b

def square(x):
return x ** 2
```

🗂️ `main.py`
```python
import mymath

print(mymath.add(2, 3)) # Output: 5


print(mymath.square(4)) # Output: 16
```

🧠 *Using `from` Keyword:*


```python
from mymath import add

print(add(10, 5))
```

📌 *Tip: Where to Store It?*


• Place the module `.py` in the same folder as your script
• Or add the folder path to `PYTHONPATH`

🔨 *Mini Project: Make a Utility Module*


🗂️ `utils.py`
```python
def is_even(n):
return n % 2 == 0

def greet(name):
return f"Hello, {name}!"
```

🗂️ `app.py`
```python
from utils import is_even, greet
print(greet("Deepak"))
print("Is 10 even?", is_even(10))
```

💡 *Make your code modular, readable & scalable!*


*React with ❤️ if you're ready for the next quiz*

Python Coding Challenge:


https://whatsapp.com/channel/0029VaiM08SDuMRaGKd9Wv0L/1661

Today, Let’s move on to the next topic in the Python Coding Challenge: 📝🧱
🔹 *Classes & Objects in Python*
Object-Oriented Programming helps you:

- Model real-world entities


- Group data + behavior together
- Write clean, scalable, and reusable code

✅ *What is a Class?*
A class is a blueprint for creating objects (instances).
It defines attributes (variables) and methods (functions).

```
class Person:
def __init__(self, name, age): # Constructor
self.name = name # Attribute
self.age = age

def greet(self): # Method


print(f"Hello, I'm {self.name} and I'm {self.age} years old.")```

✅ *What is an Object?*
An object is an instance of a class.

```p1 = Person("Alice", 25)


p1.greet()
# Output: Hello, I'm Alice and I'm 25 years old.```
🔍 *What is ___init___?*
It’s the constructor method in Python.
It runs automatically when you create a new object and is used to initialize attributes.

🔨 *Mini Project: Student Grade Tracker*


```
class Student:
def __init__(self, name):
self.name = name
self.grades = []

def add_grade(self, grade):


self.grades.append(grade)

def average(self):
if self.grades:
return sum(self.grades) / len(self.grades)
return 0

def report(self):
print(f"{self.name}'s Average Grade: {self.average():.2f}")

# Usage
s1 = Student("Deepak")
s1.add_grade(85)
s1.add_grade(92)
s1.add_grade(78)
s1.report()```

*Output:*

Deepak's Average Grade: 85.00

🔑 *OOP Concepts Practiced* :


- Class and object creation
- Initializing attributes with __init__
- Using methods to manipulate internal data
*React with ❤️ if you're ready for the next quiz*
Python Coding Challenge:
https://whatsapp.com/channel/0029VaiM08SDuMRaGKd9Wv0L/1661

Today, Let’s move on to the next topic in the Python Coding Challenge: 🧬✨
🔹 *Inheritance & Polymorphism*
🤔 *What is Inheritance?*
Inheritance lets you create a new class (child) that reuses code from an existing class (parent).

This means:

- Less repetition
- Better code organization
- Easy extensions to functionality

✅ *Basic Inheritance Example*


```class Animal:
def __init__(self, name):
self.name = name

def speak(self):
print(f"{self.name} makes a sound.")

class Dog(Animal): # Dog inherits from Animal


def speak(self):
print(f"{self.name} says Woof!")

class Cat(Animal):
def speak(self):
print(f"{self.name} says Meow!")```

🐶 *Using the Subclasses*


```d = Dog("Bruno")
c = Cat("Luna")
d.speak() # Bruno says Woof!
c.speak() # Luna says Meow!```

🔄 *What is Polymorphism?*
Polymorphism means different objects can use the same method name, but behave differently.

In the example above, Dog and Cat both have a speak() method, but each produces a different
output.

🔨 *Mini Project: RPG Character System*


Let’s model a simple RPG system with inheritance and polymorphism:

```class Character:
def __init__(self, name, level):
self.name = name
self.level = level

def attack(self):
print(f"{self.name} attacks with a basic strike.")

class Warrior(Character):
def attack(self):
print(f"{self.name} swings a sword with strength level {self.level}!")

class Mage(Character):
def attack(self):
print(f"{self.name} casts a fireball with power level {self.level}!")

# Usage
c1 = Warrior("Thor", 5)
c2 = Mage("Merlin", 7)

c1.attack() # Thor swings a sword with strength level 5!


c2.attack() # Merlin casts a fireball with power level 7!```

🔑 *Concepts Practiced:*
- Inheriting properties from a parent class
- Overriding methods for customized behavior
- Using the same method name for different outcomes (polymorphism)

*React with ❤️ if you're ready for the next quiz*


Python Coding Challenge:
https://whatsapp.com/channel/0029VaiM08SDuMRaGKd9Wv0L/1661

Today, Let’s move on to the next topic in the Python Coding Challenge:

👨‍💻 *Dunder (Magic) Methods in Python*


Let’s dive into the world of Python’s dunder methods — the ones surrounded by double
underscores (`_like_this_`)!

🔍 *What are Dunder Methods?*


Dunder (Double UNDERscore) methods are special methods in Python that let you define how
objects behave with built-in functions and operators.

✨ *Examples:*
- `_init_()` → Object initialization
- `_str_()` → String representation
- `_len_()` → Length using `len()`
- `_add_()` → `+` operator behavior
- `_eq_()` → `==` comparison

🧠 *Why Use Them?*


They make your class behave like built-in types (e.g., str, list, etc.)

✅ *Example:*
```
class Book:
def _init_(self, title, pages):
self.title = title
self.pages = pages

def _str_(self):
return f"{self.title} has {self.pages} pages"

def _len_(self):
return self.pages

book1 = Book("Python Basics", 300)


print(book1) # Python Basics has 300 pages
print(len(book1)) # 300
```

Without `_str_`, print(book1) shows something like `<_main_.Book object at 0x...>`


Without `_len_`, `len(book1)` raises an error.

🔧 *Popular Dunder Methods & Their Purpose:*


• `_init_` → Constructor
• `_str_` → Readable string output
• `_repr_` → Debug representation
• `_len_` → Length with `len()`
• `_eq_` → Equality `==` check
• `_add_` → Add with `+`
• `_getitem_` → Indexing `obj[index]`

*React with ❤️ if you're ready for the next topic*


Python Coding Challenge:
https://whatsapp.com/channel/0029VaiM08SDuMRaGKd9Wv0L/1661

Today, Let’s move on to the next topic in the Python Coding Challenge: 🏦💳
🔹 *OOP Mini Project — Bank Account System*
This project ties together everything you've learned in OOP so far:

- Classes & Objects


- Attributes and Methods
- Constructors (__init__)
- Custom behaviors

✅ *Project: Simple Bank Account*


We’ll create a class that mimics a real-world bank account where you can:

- Deposit money
- Withdraw money
- Check your balance

🧱 *Step-by-step Code:*
```
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance

def deposit(self, amount):


if amount > 0:
self.balance += amount
print(f"Deposited ₹{amount}. New balance: ₹{self.balance}")
else:
print("Deposit amount must be positive.")

def withdraw(self, amount):


if 0 < amount <= self.balance:
self.balance -= amount
print(f"Withdrew ₹{amount}. New balance: ₹{self.balance}")
else:
print("Insufficient funds or invalid amount.")

def check_balance(self):
print(f"{self.owner}, your balance is ₹{self.balance}")```

🔁 *Using the Class*


account1 = BankAccount("Deepak", 1000)

account1.deposit(500) # Deposited ₹500. New balance: ₹1500


account1.withdraw(200) # Withdrew ₹200. New balance: ₹1300
account1.check_balance() # Deepak, your balance is ₹1300

🔎 *What Did You Learn?*


- How to manage state using attributes
- How to define custom methods
- Basic validation logic inside class methods
- Using default arguments (balance=0)
- Real-world OOP design principles

*React with ❤️ if you're ready for the next topic*


Python Coding Challenge:
https://whatsapp.com/channel/0029VaiM08SDuMRaGKd9Wv0L/1661

Today, Let’s move on to the next topic in the Python Coding Challenge: 🎯📚
🔹 *OOP Review + Quiz App Project*
We'll build a console-based quiz app using:

- Classes & Objects


- Attributes & Methods
- Input handling
- Simple logic to track scores

✅ *Step 1: Create a Question Class*


```class Question:
def __init__(self, prompt, answer):
self.prompt = prompt
self.answer = answer```

Each object of this class will represent one quiz question.

✅ *Step 2: Define the Questions*


```questions = [
Question("What is the capital of India?\n(a) Delhi\n(b) Mumbai\n(c) Kolkata\n", "a"),
Question("Which language is known as the language of the web?\n(a) Python\n(b)
JavaScript\n(c) C++\n", "b"),
Question("What does OOP stand for?\n(a) Object Oriented Programming\n(b) Original Open
Platform\n(c) Other Output Package\n", "a")
]```

✅ *Step 3: Create the Quiz Logic*


```def run_quiz(questions):
score = 0
for q in questions:
answer = input(q.prompt)
if answer.lower() == q.answer:
score += 1
print(f"You got {score}/{len(questions)} correct!")```

✅ *Step 4: Run the App*


```run_quiz(questions)```

🧠 *What You Practiced:*


- Creating custom classes
- Managing collections of objects
- User input handling
- Conditional logic
- Tracking and displaying scores

🔁 *Optional Enhancements (Try these later):*


- Shuffle the questions
- Add difficulty levels
- Track high scores
- Timer for each question
- Save results to a file

*React with ❤️ if you're ready for the next topic*


Python Coding Challenge:
https://whatsapp.com/channel/0029VaiM08SDuMRaGKd9Wv0L/1661

Today, Let’s move on to the next topic in the Python Coding Challenge:

🚀 *Working with JSON & APIs in Python* 🌍📡


🔹 *What is JSON?*
JSON (JavaScript Object Notation) is a lightweight data format used for storing and exchanging
data between systems (especially in web APIs).

It looks like this:

{
"name": "Alice",
"age": 30,
"skills": ["Python", "SQL"]
}

Python treats JSON data like dictionaries and lists.

✅ *How to Handle JSON in Python*


```import json
# Convert Python dict to JSON string
person = {"name": "Alice", "age": 30}
json_string = json.dumps(person)
print(json_string)

# Convert JSON string to Python dict


data = '{"name": "Bob", "age": 25}'
person_dict = json.loads(data)
print(person_dict["name"]) # Output: Bob```

🔹 *What is an API?*
An API (Application Programming Interface) allows different systems to talk to each other.
You send a request → you get a response (usually in JSON).

✅ *Making a Simple API Call (using mock data)*


```import requests

response = requests.get("https://jsonplaceholder.typicode.com/users/1")
data = response.json()

print(f"Name: {data['name']}")
print(f"Email: {data['email']}")```

This fetches data from a public fake API and prints the name and email of a user.

🔨 *Mini Project: Mock Weather App*


```import requests

def get_weather():
city = input("Enter your city: ")
print(f"Fetching weather for {city}...")

# Mock response structure


weather_data = {
"Delhi": {"temp": "32°C", "condition": "Sunny"},
"Mumbai": {"temp": "28°C", "condition": "Rainy"},
}

if city in weather_data:
info = weather_data[city]
print(f"Temperature: {info['temp']}, Condition: {info['condition']}")
else:
print("Sorry, no data available.")

get_weather()```

🔑 *What You Practiced* :


- JSON serialization/deserialization
- Making HTTP requests using requests
- Accessing and using API response data
- Mocking real-world scenarios

*React with ❤️ if you're ready for the next topic*


Python Coding Challenge:
https://whatsapp.com/channel/0029VaiM08SDuMRaGKd9Wv0L/1661

Now, Let’s move on to the next topic in the Python Coding Challenge:

*Web Scraping (Mocked) in Python* 🕸️🧠


🔹 *What is Web Scraping?*
Web scraping means writing code to fetch and extract data from web pages.

We usually use:

- requests → to download the HTML


- BeautifulSoup → to parse and extract data from HTML

✅ *Step-by-Step Mock Scraping Example*


🔸 Imagine this is our webpage (stored as a string):
html = """
<html>
<body>
<h1>Top Programming Languages</h1>
<ul>
<li>Python</li>
<li>JavaScript</li>
<li>Java</li>
</ul>
</body>
</html>
"""

🔸 *Parse It Using BeautifulSoup*


```
from bs4 import BeautifulSoup

soup = BeautifulSoup(html, "html.parser")

# Extracting the heading


heading = soup.find("h1").text
print("Heading:", heading)

# Extracting the list items


languages = soup.find_all("li")
for lang in languages:
print("Language:", lang.text)```

✅ *Output* :
Heading: Top Programming Languages
Language: Python
Language: JavaScript
Language: Java

🔎 *Why Use Web Scraping?*


- Collect product prices from e-commerce sites
- Grab job listings from job boards
- Gather headlines or articles from news sites
- Monitor stock prices or crypto values
(Always follow website terms of service before scraping real websites)

🔨 *Mini Task: Extract Blog Titles*


Here’s another HTML string you can experiment with:

html = """
<div>
<h2>Python for Beginners</h2>
<h2>Data Analysis with Pandas</h2>
<h2>Machine Learning Crash Course</h2>
</div>
"""

soup = BeautifulSoup(html, "html.parser")


titles = soup.find_all("h2")

for t in titles:
print("Blog Title:", t.text)

🔑 *What You Practiced:*


- Parsing HTML with BeautifulSoup
- Using find() and find_all()
- Navigating a page's structure
- Extracting content programmatically

*React with ❤️ if you're ready for the next topic*


Python Coding Challenge:
https://whatsapp.com/channel/0029VaiM08SDuMRaGKd9Wv0L/1661

Now, Let’s move on to the next topic in the Python Coding Challenge:

*Regular Expressions (RegEx) in Python*

🔍📜
Today you’ll learn how to search, match, and extract patterns in text using Python’s re module
— a powerful tool for working with strings!

🔹 *What is a Regular Expression?*


A regular expression (RegEx) is a sequence of characters that forms a search pattern. It’s
commonly used for:

- Email and phone number validation


- Searching for patterns in text
- Data cleaning and extraction

✅ *Python’s re Module – Basics*


import re
🔸 *1. re.search() –* Looks for a match anywhere in the string
text = "My email is hello@example.com"
match = re.search(r"\w+@\w+\.\w+", text)

if match:
print("Found:", match.group())

✅ Output: Found: hello@example.com


🔸 *2. re.findall() –* Returns all matches as a list
text = "Emails: one@mail.com and two@site.org"
emails = re.findall(r"\w+@\w+\.\w+", text)
print(emails)

✅ Output: ['one@mail.com', 'two@site.org']


🔸 *3. re.sub() – Replaces all matches*
text = "Hello 123, this is test 456"
cleaned = re.sub(r"\d+", "*", text)
print(cleaned)

✅ Output: Hello *, this is test *


🔹 *Common Patterns*
- Pattern​ Description

\d​ Any digit (0-9)


\w​ Any alphanumeric character
\s​ Any whitespace (space/tab)
.​ Any character (except newline)
+​ One or more repetitions
*​ Zero or more repetitions
^​ Start of string
$​ End of string

🔨 *Mini Task: Extract Phone Numbers*


text = "Call me at 9876543210 or 9123456789"
numbers = re.findall(r"\d{10}", text)
print("Phone numbers found:", numbers)

✅ Output: ['9876543210', '9123456789']


🔑 *What You Practiced* :
- Writing and using regular expressions
- Using re.search(), re.findall(), and re.sub()
- Cleaning and extracting patterns from text
- Real-world data handling

*React with ❤️ if you're ready for the next topic*


Python Coding Challenge:
https://whatsapp.com/channel/0029VaiM08SDuMRaGKd9Wv0L/1661

Now, Let’s move on to the next topic in the Python Coding Challenge:

📅 Tkinter GUI (Intro)* 🎨🖱️


*

Let’s bring Python to life with desktop apps using *Tkinter* — Python’s built-in GUI library!

🔸 *What is Tkinter?*
🖲️ *Buttons*
It’s used to create GUI apps with:

🏷️ *Labels*
📝 *Text Boxes*
🪟 *Windows*
🛠️ *Basic Tkinter Code:*
```
import tkinter as tk

root = tk.Tk()
root.title("My First GUI")
root.geometry("300x200")

label = tk.Label(root, text="Hello, Tkinter!")


label.pack()

root.mainloop()
```

🔍 *What’s Happening?*
- `tk.Tk()` → Creates the main window
- `Label()` → Widget to display text
- `pack()` → Places the widget
- `mainloop()` → Keeps the window open

🔹 *Popular Widgets:*
📌 *Label* – Display text
📌 *Button* – Trigger actions
📌 *Entry* – Text input (1 line)
📌 *Text* – Multi-line input
📌 *Frame* – Group widgets
🧠 *Use Cases:*
✅ Calculators
✅ Data entry forms
✅ Small desktop tools
✅ Educational apps
🎯 Tkinter is *perfect for quick tools & UIs*. No need for big frameworks when a simple GUI
does the job.

*React with ❤️ if you're ready for the next topic*


Python Coding Challenge:
https://whatsapp.com/channel/0029VaiM08SDuMRaGKd9Wv0L/1661

Now, Let’s move on to the next topic in the Python Coding Challenge:

*📅 Tkinter Widgets & Events* 💡🖱️


Time to make your Python GUI *interactive*!

🔹 *Create Buttons & Entry Fields:*


```
import tkinter as tk

def greet():
user_input = entry.get()
label.config(text=f"Hello, {user_input}!")

root = tk.Tk()
root.title("Greet App")
root.geometry("300x150")

entry = tk.Entry(root)
entry.pack(pady=5)

button = tk.Button(root, text="Greet Me", command=greet)


button.pack(pady=5)

label = tk.Label(root, text="Your greeting will appear here.")


label.pack(pady=10)

root.mainloop()
```

🧠 *Key Concepts:*
✅ `Entry()` – Text input
✅ `Button()` – Click to trigger function
✅ `command=greet` – Calls greet function
✅ `.get()` – Get input from user
✅ `.config()` – Change widget properties
🔸 *Common Widgets Overview:*
• `Label` → `.config()` (change text)
• `Entry` → `.get()` (get user input)
• `Button` → `command=` (handle click)
• `Checkbutton` → `.get()` (true/false)
• `Radiobutton` → `.get()` (selected option)

🔔 *Event-Driven Programming:*
✔️ Button click
Your app *waits* for user actions like:

✔️ Typing
✔️ Mouse movement
💡 *What can you build?*
🧮 Calculator
🔐 Login form
📝 To-do list
*React with ❤️ if you're ready for the next topic*

Python Coding Challenge:


https://whatsapp.com/channel/0029VaiM08SDuMRaGKd9Wv0L/1661
Now, Let’s move on to the next topic in the Python Coding Challenge:

✅ *CLI Tools: Build a Command-Line Calculator using argparse*


🔍 *What You'll Learn:*
- How to use argparse to handle command-line arguments
- Writing modular and scalable command-line tools
- Basic CLI interaction: add, subtract, multiply, divide

🧠 *Python Code: Basic CLI Calculator*


```
import argparse

def main():
parser = argparse.ArgumentParser(description="A simple CLI calculator")

parser.add_argument("num1", type=float, help="First number")


parser.add_argument("num2", type=float, help="Second number")
parser.add_argument("operation", choices=["add", "sub", "mul", "div"], help="Operation to
perform")

args = parser.parse_args()

if args.operation == "add":
result = args.num1 + args.num2
elif args.operation == "sub":
result = args.num1 - args.num2
elif args.operation == "mul":
result = args.num1 * args.num2
elif args.operation == "div":
if args.num2 == 0:
result = "Error: Cannot divide by zero!"
else:
result = args.num1 / args.num2

print("Result:", result)

if __name__ == "__main__":
main()
```
🧪 *How to Run It from Command Line:*
```python cli_calculator.py 10 5 add
# Output: Result: 15.0```

*React with ❤️ if you're ready for the next topic*


Python Coding Challenge:
https://whatsapp.com/channel/0029VaiM08SDuMRaGKd9Wv0L/1661
Now, Let’s move on to the next topic in the Python Coding Challenge:

*Python Automation — File Organizer Script*

Let’s automate a real-world task today: organizing files in a folder based on their file types. This
is one of the coolest and most practical Python use-cases.

🧠 *Concepts You’ll Learn*


- os and shutil modules
- Automating file movement
- Using file extensions to categorize files

💻 *Project: File Organizer Script*


This script will:

1. Look at all the files in a folder.


2. Check their file extensions (like .jpg, .pdf, .mp3, etc.).
3. Move them to folders named “Images”, “PDFs”, “Music”, etc.

✅ *Sample Code:*
```import os
import shutil

# Define the folder to organize


folder_path = "your-folder-path-here" # e.g. r"C:\Users\YourName\Downloads"

# File types and their categories


file_types = {
"Images": [".jpg", ".jpeg", ".png", ".gif"],
"Documents": [".pdf", ".docx", ".txt", ".xlsx"],
"Videos": [".mp4", ".mkv", ".mov"],
"Music": [".mp3", ".wav"],
"Archives": [".zip", ".rar", ".tar"]
}

def organize_files():
for file in os.listdir(folder_path):
filename, ext = os.path.splitext(file)
ext = ext.lower()

for category, extensions in file_types.items():


if ext in extensions:
category_path = os.path.join(folder_path, category)
if not os.path.exists(category_path):
os.mkdir(category_path)
shutil.move(
os.path.join(folder_path, file),
os.path.join(category_path, file)
)
break # Stop checking other categories

print("✅ Files organized successfully!")


organize_files()```

🔍 *Try it Yourself*
- Add a few test files to a sample folder.
- Run the script and see them neatly sorted!
- You can add more categories based on your needs.

*React with ❤️ for more*


Python Coding Challenge:
https://whatsapp.com/channel/0029VaiM08SDuMRaGKd9Wv0L/1661

Now, Let’s move on to the next topic in the Python Coding Challenge:

🎉 *Final Python Project – Build a Weather App (using API + Tkinter)*


You've made it to the final day — let’s combine everything you’ve learned and build something
awesome from scratch.
Now, you’ll create a Weather App that shows the current weather of any city using an API and a
graphical interface with Tkinter.

🧠 *Concepts You’ll Use*


- Working with APIs (requests)
- Building GUI using Tkinter
- Error handling & clean UI design

🧪 *Prerequisite*
Sign up at https://openweathermap.org/api and get your free API key.

💻 *Project: Weather App (Tkinter + OpenWeatherMap API)*


```import requests
from tkinter import *

def get_weather():
city = city_entry.get()
api_key = "YOUR_API_KEY" # Replace this with your OpenWeatherMap API key
url =
f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"

try:
response = requests.get(url)
data = response.json()

if data["cod"] == 200:
temp = data["main"]["temp"]
desc = data["weather"][0]["description"]
result_label.config(text=f"{city.title()}:\n{temp}°C, {desc}")

😞
else:
result_label.config(text="City not found ")
except:
result_label.config(text="Network error. Try again.")

# GUI Setup
root = Tk()
root.title("Weather App")
root.geometry("300x200")
city_entry = Entry(root, width=30)
city_entry.pack(pady=10)
city_entry.insert(0, "Enter City Name")

get_button = Button(root, text="Get Weather", command=get_weather)


get_button.pack()

result_label = Label(root, text="", font=("Helvetica", 12), pady=10)


result_label.pack()

root.mainloop()```

🚀 *Bonus Ideas*
- Show temperature in Fahrenheit too
- Add weather icons
- Save search history
- Show country name and wind speed

🏁 Congratulations!
You’ve just completed a full 30-day Python learning journey:

- Mastered syntax, functions, OOP, error handling


- Built CLI tools, games, automations, and GUI apps
- Used APIs and explored real-life use cases

You're now ready for freelancing, internships, or personal projects.

*React with ❤️ for more Python Resources & Learning Series in the future*
Python Coding Challenge:
https://whatsapp.com/channel/0029VaiM08SDuMRaGKd9Wv0L/1661

You might also like