Python basic to advance
43 subscribers
131 photos
98 links
Learn Python daily with bite-sized lessons, code examples, output previews, and fun quizzes. Perfect for beginners and enthusiasts!
Download Telegram
🚀 **Day 1: Your Python Journey Begins!** 🐍

Welcome to the very first step of our Python learning series! Today, we're diving straight into the basics with the legendary "Hello, World!" program. It's the simplest way to confirm your setup works and celebrate your first line of code. Get ready to write, run, and feel the magic! ✨ Let's make some noise!

Here's your first piece of Python code:

```python
print("Hello, World!")
```

Output example:
```
Hello, World!
```

💪 **Your challenge:**
1. Change the text inside the `print()` function to say "Hello, Python Learners!"
2. Try printing your own name!

---
Day 1: Introduction to Python with Hello World \- Code & Output
🚀 Welcome back, aspiring Pythonistas!

After a fantastic Day 1 intro, it's time to dive into the fundamental building blocks of any program: *Variables and Data Types*! 🧱

Think of variables as named containers for storing information. And data types? They tell Python what kind of information that is – numbers, text, true/false values, and more! Understanding these is crucial for writing dynamic and useful code. Let's get hands-on! 💻

---

```python
# Day 2: Variables and Data Types

# 1. Variable Assignment (creating containers for data)
student_name = "Alice Smith" # A string (text)
student_age = 20 # An integer (whole number)
gpa = 3.85 # A float (decimal number)
is_enrolled = True # A boolean (True/False)

# 2. Printing Values and their Data Types
print(f"Name: {student_name}, Type: {type(student_name)}")
print(f"Age: {student_age}, Type: {type(student_age)}")
print(f"GPA: {gpa}, Type: {type(gpa)}")
print(f"Is Enrolled: {is_enrolled}, Type: {type(is_enrolled)}")

# 3. Reassigning a variable (changing the content of a container)
student_age = 21 # Alice had a birthday!
print(f"nAlice's new age: {student_age}")

# You can also use single quotes for strings
course_name = 'Introduction to Python'
print(f"Course: {course_name}")
```

---

Output example:
```
Name: Alice Smith, Type: <class 'str'>
Age: 20, Type: <class 'int'>
GPA: 3.85, Type: <class 'float'>
Is Enrolled: True, Type: <class 'bool'>

Alice's new age: 21
Course: Introduction to Python
```

---

💡 **Your Challenge:**
Create three new variables:
1. `city` (a string for your hometown)
2. `population` (an integer)
3. `average_temp` (a float)
Then, print all three variables along with their respective data types using the `type()` function! Share your code or output in the comments! 👇

---
Which of the following is NOT a valid Python variable name?
Anonymous Quiz
0%
my_variable
0%
_private_data
0%
2nd_attempt
0%
user_count
Here's your Telegram post and quiz question!

---

🚀 Day 4: Time to make your Python programs smart! Today, we're mastering *Conditional Statements*: `if`, `elif`, and `else`. 🤖 These powerful tools let your code make decisions and execute different blocks of instructions based on specific conditions. No more rigid scripts – let's add some flexible logic! Get ready to control the flow of your programs like a pro! 👇

```python
# Day 4: Conditional Statements (if, elif, else)

# Get a score from the user
score = int(input("Enter your test score (0-100): "))

# Use if, elif, else to assign a grade based on the score
if score >= 90:
print("🎉 Excellent! You got an A!")
elif score >= 75:
print("👍 Good job! You got a B.")
elif score >= 50:
print("✅ You passed! Keep practicing.")
else:
print("🙁 Needs improvement. Don't give up!")

print("Program finished.")
```

Output example:
```
Enter your test score (0-100): 78
👍 Good job! You got a B.
Program finished.
```

✨ **Your Challenge:** Modify the code above! Add an `elif` condition to print 'Amazing!' if the score is exactly 100. How would you adjust the existing `if score >= 90` condition to fit this new rule? 🤔

---
Day 4: Conditional Statements \(if, elif, else\) \- Code & Output
What will be the output of the following Python code snippet?
```python
number = 10 if number > 15: message = "High" elif number == 10: message = "Exact" elif number < 12: message = "Low" else: message = "Other" print(message) ```
Anonymous Quiz
0%
High
100%
Exact
0%
Low
0%
Other
Here's your Telegram post for Day 5 of the Python learning series!

---

**Day 5: Loops (for and while) 🔄**

Hello, Python learners! 👋 Today we're diving into the powerful world of loops! Loops are absolutely essential for automating repetitive tasks and making your code super efficient. We'll explore two main types: `for` loops, perfect for iterating over sequences like lists or ranges, and `while` loops, which repeat as long as a certain condition remains true. Get ready to automate! 🚀

```python
# --- Python Loops: for and while ---

print("--- For Loop Example (Iterating over a list) ---")
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I love {fruit}!")

print("n--- While Loop Example (Counting) ---")
count = 0
while count < 3:
print(f"Count is {count}")
count += 1 # IMPORTANT: Increment to avoid an infinite loop!

print("n--- For Loop with range() ---")
for i in range(4): # This will iterate for i = 0, 1, 2, 3
print(f"Number from range: {i}")

print("n--- For Loop with else (optional!) ---")
for char_code in [65, 66, 67]:
print(f"Character: {chr(char_code)}")
else:
print("All characters processed!")
```

Output example:
```
--- For Loop Example (Iterating over a list) ---
I love apple!
I love banana!
I love cherry!

--- While Loop Example (Counting) ---
Count is 0
Count is 1
Count is 2

--- For Loop with range() ---
Number from range: 0
Number from range: 1
Number from range: 2
Number from range: 3

--- For Loop with else (optional!) ---
Character: A
Character: B
Character: C
All characters processed!
```

💡 **Your Challenge:**
1. Use a `while` loop to print numbers from 5 down to 1.
2. Then, use a `for` loop to print each character in the word "Python" on a separate line.

Share your solutions or questions in the comments! 👇 Happy coding! ✨

---
Day 5: Loops \(for and while\) \- Code & Output
What will be the output of the following Python code snippet?

```python result = "" for i in range(4): if i == 2: break result += str(i) print(result) ```
Anonymous Quiz
0%
012
50%
01
50%
0123
0%
0
🚀 **Python Learning Series - Day 6: Functions in Python!** 🚀

Hello, amazing learners! ✨ Today, we're diving into one of the most fundamental and powerful concepts in Python: **Functions**! Functions allow us to write reusable blocks of code, making our programs organized, efficient, and easier to understand. No more repetitive code! Let's unlock the magic of `def`! 🔑

---

```python
# 1. Defining a simple function
def greet_user(name):
"""This function greets the user by name."""
print(f"Hello, {name}! Welcome to Day 6 of our Python journey. 👋")

# 2. Calling the function
greet_user("Pythonista")

# 3. Function with parameters and a return value
def calculate_sum(num1, num2):
"""This function takes two numbers and returns their sum."""
total = num1 + num2
return total

# 4. Using the returned value
result = calculate_sum(15, 25)
print(f"The sum of 15 and 25 is: {result}")

# 5. Another call
greet_user("Beginner")
```

---

Output example:
```
Hello, Pythonista! Welcome to Day 6 of our Python journey. 👋
The sum of 15 and 25 is: 40
Hello, Beginner! Welcome to Day 6 of our Python journey. 👋
```

---

💡 **Your Challenge:**
Write a Python function called `get_fahrenheit` that takes a temperature in Celsius as a parameter and returns the temperature in Fahrenheit. (Formula: `F = C * 9/5 + 32`). Then, call your function with a sample Celsius value and print the result! Share your code snippets below! 👇

---
Which keyword is used to define a function in Python?
Anonymous Quiz
0%
function
100%
def
0%
func
0%
define
Here's your Telegram post and quiz question:

---

✨🐍 **Python Learning Series - Day 7: Lists and Tuples!** 🧠💡

Hello future Pythonistas! Today, we're diving into two fundamental data structures: **Lists** and **Tuples**. Both are ordered collections, but they have a crucial difference: lists are *mutable* (you can change them after creation), while tuples are *immutable* (they cannot be changed). Understanding this distinction is key to writing robust Python code! Let's explore. 👇

```python
# --- Lists: Mutable Ordered Collections ---
my_fruits = ["apple", "banana", "cherry"]
print(f"My fruit list: {my_fruits}")

# Lists are mutable: we can add, remove, or change elements
my_fruits.append("date")
print(f"After adding 'date': {my_fruits}")

my_fruits[0] = "apricot" # Change the first element
print(f"After changing 'apple' to 'apricot': {my_fruits}")

# --- Tuples: Immutable Ordered Collections ---
my_coordinates = (10.0, 20.5)
print(f"My coordinates tuple: {my_coordinates}")

# Tuples are immutable: once created, you cannot change their elements
# my_coordinates.append(30.0) # This would cause an error!
# my_coordinates[0] = 5.0 # This would also cause an error!

# You can access elements in both by index
print(f"Second fruit: {my_fruits[1]}")
print(f"X coordinate: {my_coordinates[0]}")

# You can even have a list of tuples or a tuple of lists!
user_profiles = [("Alice", 28), ("Bob", 34)]
print(f"User profiles (list of tuples): {user_profiles}")
```

Output example:
```
My fruit list: ['apple', 'banana', 'cherry']
After adding 'date': ['apple', 'banana', 'cherry', 'date']
After changing 'apple' to 'apricot': ['apricot', 'banana', 'cherry', 'date']
My coordinates tuple: (10.0, 20.5)
Second fruit: banana
X coordinate: 10.0
User profiles (list of tuples): [('Alice', 28), ('Bob', 34)]
```

🔥 **Small Challenge:**
Create a list called `my_favorite_movies` and add 3 movie titles. Then, create a tuple called `my_birth_date` with your birth year, month, and day. Try to add a fourth movie to your list and then try to change the month in your birth date tuple. What happens? Share your thoughts or code in the comments!

---
Which of the following Python data structures is immutable?
Anonymous Quiz
50%
list
0%
set
50%
tuple
0%
dictionary
Here's your Telegram post and quiz for Day 8:

---

👋 Hey Python Learners! 🚀 Welcome to Day 8 of our coding journey!

Today, we're unlocking the power of two incredibly versatile data structures: **Dictionaries** and **Sets**! 🧠 Dictionaries are your go-to for storing data in key-value pairs, perfect for mapping information like names to ages, or products to prices. Think of them as super-fast lookup tables! 📚

Then, we'll explore **Sets** – collections of unique items. They're fantastic for filtering out duplicates and performing mathematical set operations like unions and intersections. Get ready to organize your data like a pro! ✨

```python
# Day 8: Dictionaries & Sets

# --- Dictionaries ---
# Create a dictionary
student_scores = {
"Alice": 85,
"Bob": 92,
"Charlie": 78
}
print("Initial scores:", student_scores)

# Access a value by its key
print("Bob's score:", student_scores["Bob"])

# Add a new entry
student_scores["David"] = 95
print("Scores after adding David:", student_scores)

# Update an existing entry
student_scores["Alice"] = 88
print("Alice's updated score:", student_scores["Alice"])

# Loop through a dictionary's items
print("n--- Looping through scores ---")
for name, score in student_scores.items():
print(f"{name}: {score}")

# --- Sets ---
# Create a set (duplicates are automatically removed!)
my_numbers = {1, 2, 3, 2, 4, 1}
print("nUnique numbers in a set:", my_numbers)

# Add an element to a set
my_numbers.add(5)
print("Numbers after adding 5:", my_numbers)

# Set operations - Example: Union and Intersection
prime_numbers = {2, 3, 5, 7}
even_numbers = {2, 4, 6, 8}

# Union: Elements in either set
print("Primes OR Evens (Union):", prime_numbers.union(even_numbers))

# Intersection: Elements common to both sets
print("Primes AND Evens (Intersection):", prime_numbers.intersection(even_numbers))
```

Output example:
```
Initial scores: {'Alice': 85, 'Bob': 92, 'Charlie': 78}
Bob's score: 92
Scores after adding David: {'Alice': 85, 'Bob': 92, 'Charlie': 78, 'David': 95}
Alice's updated score: 88

--- Looping through scores ---
Alice: 88
Bob: 92
Charlie: 78
David: 95

Unique numbers in a set: {1, 2, 3, 4}
Numbers after adding 5: {1, 2, 3, 4, 5}
Primes OR Evens (Union): {2, 3, 4, 5, 6, 7, 8}
Primes AND Evens (Intersection): {2}
```

### 💡 Small Challenge:
You have a list of cities visited by two friends:
`friend_a_cities = {"Paris", "London", "Rome", "Berlin"}`
`friend_b_cities = {"London", "Rome", "Madrid", "Barcelona"}`

1. Find all cities that *both* friends visited.
2. Find all unique cities visited by *at least one* friend.
3. Find cities visited by `friend_a` but *not* by `friend_b`.

(Hint: Use set operations! 😉)

---
Day 8: Dictionaries and Sets \- Code & Output
Here's your Telegram post for Day 9: String Manipulation, along with the quiz question:

---

🌟 Day 9 of our Python journey is here, and it's all about **String Manipulation**! 🐍 Strings are fundamental for handling text data, from messages to file paths. Today, we'll dive into powerful techniques like *slicing*, *method calls* (think `replace()`!), and the incredibly useful *f-strings* for dynamic text formatting. Get ready to transform your text like a pro! ✨

```python
# Our main string for today!
message = "Hello, Python Learners! Welcome to Day 9 of our series."

print(f"Original message: '{message}'")
print(f"Length of message: {len(message)}")

# --- 1. String Slicing ---
# Extract a portion of the string
first_word = message[0:5] # From index 0 up to (but not including) 5
learning_topic = message[7:23] # "Python Learners!"

print(f"nFirst word (slice): '{first_word}'")
print(f"Learning topic (slice): '{learning_topic}'")

# --- 2. String Methods ---
# Using .replace() to swap words
modified_message = message.replace("Python Learners", "Coding Enthusiasts")

# Using .upper() and .lower()
uppercase_part = message[25:32].upper() # "WELCOME"
lowercase_part = message[0:5].lower() # "hello"

print(f"nMessage after replace(): '{modified_message}'")
print(f"Uppercase part: '{uppercase_part}'")
print(f"Lowercase part: '{lowercase_part}'")

# --- 3. F-strings (Formatted String Literals) ---
# Embed expressions directly inside string literals
day_number = 9
lesson_topic = "String Manipulation"
formatted_output = f"🚀 Today is Day {day_number}, and we're mastering {lesson_topic}!"

print(f"nUsing f-string for dynamic output: {formatted_output}")
```

Output example:
```
Original message: 'Hello, Python Learners! Welcome to Day 9 of our series.'
Length of message: 57

First word (slice): 'Hello'
Learning topic (slice): 'Python Learners!'

Message after replace(): 'Hello, Coding Enthusiasts! Welcome to Day 9 of our series.'
Uppercase part: 'WELCOME'
Lowercase part: 'hello'

Using f-string for dynamic output: 🚀 Today is Day 9, and we're mastering String Manipulation!
```

🔥 **CHALLENGE:** Can you extract the phrase "our series" from the `message` variable using slicing, and then print it backwards using slicing (e.g., `series ruo`)? Share your solution! 👇

---