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
Here's your Telegram post for Day 4 of the Python learning series!

---

**Python Learning Series: Day 4 - Conditional Statements**

Day 4 is here! 🚀 Today, we unlock the power of *decision-making* in Python with Conditional Statements: `if`, `elif`, and `else`.

Ever wanted your code to do different things based on certain conditions? 🤔 That's exactly what these statements let you do! They're fundamental for creating dynamic and intelligent programs. Let's dive into controlling your code's flow! 👇

```python
# Example 1: Checking if a number is positive, negative, or zero
number = 5 # Try changing this to 0 or -3 and run the code!

if number > 0:
print("The number is positive.")
elif number == 0:
print("The number is zero.")
else:
print("The number is negative.")

print("-" * 20) # Separator for clarity

# Example 2: Simple age check
age = 18

if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
```

Output example:
```
The number is positive.
--------------------
You are an adult.
```

Small challenge:
Ready for a quick practice? 🤔 Write a Python script that takes a user's `input()` number and determines if it's "Even" or "Odd" using `if` and `else` statements! (Hint: The modulo operator `%` might be your friend here! 😉)

---
Day 4: Conditional Statements \(if, elif, else\) \- Code & Output
What will be the output of the following Python code?
```python
score = 75 if score >= 90: result = "Excellent" elif score >= 70: result = "Good" elif score >= 50: result = "Average" else: result = "Fail" print(result) ```
Anonymous Quiz
0%
Good
0%
Excellent
0%
Average
0%
Fail
Here's your Telegram post for Day 5 of the Python learning series!

---

Hello Python Learners! 👋 Day 5 is here, and we're diving into one of programming's superpowers: *loops*! 🚀 Loops allow your code to repeat actions efficiently, saving you tons of time and effort. Whether you know exactly how many times you need to repeat something (`for` loop) or you need to keep going until a condition is met (`while` loop), loops are your best friends for automation. Let's make our programs dynamic! ✨

```python
# Day 5: Loops (for and while)

# --- The 'for' Loop ---
# Used for iterating over a sequence (like a list, tuple, dictionary, set, or string)
# or other iterable objects. Great when you know how many times you want to loop.

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

print("n--- For Loop Example: Using range() ---")
# range(start, stop, step) - stop is exclusive
for i in range(3): # This will give 0, 1, 2
print(f"Counting with for: {i}")

# --- The 'while' Loop ---
# Executes a block of code as long as a specified condition is true.
# Be careful not to create an infinite loop!

print("n--- While Loop Example ---")
countdown = 3
while countdown > 0:
print(f"Countdown: {countdown}...")
countdown -= 1 # Decrement the counter to eventually make the condition false
print("Lift off! 🚀")

```

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

--- For Loop Example: Using range() ---
Counting with for: 0
Counting with for: 1
Counting with for: 2

--- While Loop Example ---
Countdown: 3...
Countdown: 2...
Countdown: 1...
Lift off! 🚀
```

**Small Challenge:** 💪
Write a `for` loop that prints all even numbers from 2 to 10 (inclusive). Share your code in the comments! 👇

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

```python count = 0 while count < 4: print(count * 2) count += 1 ```
Anonymous Quiz
0%
0 2 4 6
100%
0 1 2 3
0%
2 4 6 8
0%
0 2 4 6 8
🎉 Hey Python learners! 🚀 Ready for Day 6? Today, we're diving into the superpower of Python: *functions*! 🧱 Functions are reusable blocks of code that perform a specific task, helping you write cleaner, more organized, and less repetitive programs. Think of them as mini-programs within your main program! Let's unlock their magic! ✨

Functions are defined using the `def` keyword, followed by the function name, parentheses `()`, and a colon `:`. Parameters go inside the parentheses.

```python
# Defining a simple function to greet someone
def greet(name):
"""This function takes a name and prints a personalized greeting."""
print(f"👋 Hello, {name}! Welcome to Day 6 of Python!")

# Defining a function that performs a calculation and returns a value
def add_numbers(a, b):
"""This function takes two numbers and returns their sum."""
return a + b

# --- Calling our functions ---

# Call the greet function with different names
greet("Pythonista")
greet("Learner")

# Call the add_numbers function and store its returned value
sum_result = add_numbers(10, 5)
print(f"The sum of 10 and 5 is: {sum_result}")

another_sum = add_numbers(2.5, 7.5)
print(f"The sum of 2.5 and 7.5 is: {another_sum}")
```

Output example:
```
👋 Hello, Pythonista! Welcome to Day 6 of Python!
👋 Hello, Learner! Welcome to Day 6 of Python!
The sum of 10 and 5 is: 15
The sum of 2.5 and 7.5 is: 10.0
```

### Small Challenge:
Your turn! 🚀 Create a function called `multiply(x, y)` that takes two numbers as arguments and returns their product. Then call your `multiply` function with any two numbers and print the result!

---
Day 6: Functions in Python \- Code & Output
Which keyword is used to define a function in Python?
Anonymous Quiz
0%
func
0%
define
0%
def
0%
function
Here's your Telegram post for Day 7!

---

🐍 Python Learning Series - Day 7! ✨ Today, we dive into two fundamental data structures: *Lists* and *Tuples*! 📚 You'll learn how to store collections of items, access them, and understand the key differences between these versatile types. Get ready to organize your data like a pro! 🚀

```python
# Day 7: Lists and Tuples - Organizing Collections

# --- Lists (Mutable, ordered collection) ---
my_list = [1, 2, 3, "apple", True]
print(f"Original list: {my_list}")

# Accessing elements
print(f"First element of list: {my_list[0]}")
print(f"Last element of list: {my_list[-1]}")

# Modifying a list (Lists are mutable!)
my_list.append("banana")
print(f"List after append: {my_list}")
my_list[1] = 20 # Change an element by index
print(f"List after modification: {my_list}")
my_list.remove("apple")
print(f"List after remove: {my_list}")

# Slicing a list
print(f"List slice (index 1 to 3): {my_list[1:4]}")


# --- Tuples (Immutable, ordered collection) ---
my_tuple = (10, 20, "orange", False)
print(f"nOriginal tuple: {my_tuple}")

# Accessing elements (similar to lists)
print(f"First element of tuple: {my_tuple[0]}")
print(f"Last element of tuple: {my_tuple[-1]}")

# Tuples are IMMUTABLE - cannot change after creation!
# Uncommenting the line below would raise a TypeError:
# my_tuple[0] = 100
# print(f"Trying to modify tuple: {my_tuple}") # This will fail!

# Concatenating tuples (creates a NEW tuple)
new_tuple = my_tuple + (True, 50)
print(f"Concatenated tuple (new tuple created): {new_tuple}")

# Checking types
print(f"Type of my_list: {type(my_list)}")
print(f"Type of my_tuple: {type(my_tuple)}")
```

Output example:
```
Original list: [1, 2, 3, 'apple', True]
First element of list: 1
Last element of list: True
List after append: [1, 2, 3, 'apple', True, 'banana']
List after modification: [1, 20, 3, 'apple', True, 'banana']
List after remove: [1, 20, 3, True, 'banana']
List slice (index 1 to 3): [20, 3, True]

Original tuple: (10, 20, 'orange', False)
First element of tuple: 10
Last element of tuple: False
Concatenated tuple (new tuple created): (10, 20, 'orange', False, True, 50)
Type of my_list: <class 'list'>
Type of my_tuple: <class 'tuple'>
```

Small challenge:
Challenge: Create a list of your 3 favorite colors. Now, create a tuple containing the same colors but in a different order. Try to add a 4th color to your *tuple* and observe what happens! 🎨🖌️

---

Here's a quiz question related to today's lesson:
Day 7: Lists and Tuples \- Code & Output
🚀 Day 9 of our Python journey is here, and it's all about mastering **String Manipulation**! 🐍 Strings are fundamental in Python, and knowing how to effectively work with them is crucial for everything from data processing to user interfaces. Today, we'll dive into powerful methods to slice, dice, transform, and search text. Get ready to make your strings dance with `len()`, `split()`, `replace()`, and more! Let's code! ✨

```python
# Day 9: String Manipulation - Making text work for you!

message = " Hello Python Learners! Keep Coding! "
name = "Alice"

print("--- String Basics ---")
# 1. Length of a string
print(f"Original message: '{message}'")
print(f"Length of message: {len(message)}")

# 2. String concatenation (joining strings)
greeting = "Good morning, " + name + "!"
print(f"Concatenation: {greeting}")

# 3. String slicing (extracting parts)
first_word = message[2:7] # From index 2 up to (but not including) 7
print(f"Slicing (first word 'Hello'): '{first_word}'")
last_part = message[20:] # From index 20 to the end
print(f"Slicing (from index 20): '{last_part}'")
reversed_message = message[::-1] # A common trick for reversing
print(f"Reversed message: '{reversed_message}'")

print("n--- Transformation Methods ---")
# 4. Uppercase and Lowercase
upper_case = message.upper()
print(f"Uppercase: '{upper_case}'")
lower_case = message.lower()
print(f"Lowercase: '{lower_case}'")

# 5. Replacing parts of a string
modified_message = message.replace("Coding", "Learning")
print(f"Replace 'Coding' with 'Learning': '{modified_message}'")

# 6. Splitting a string into a list of words/parts
sentence = "Python is super fun"
words = sentence.split(" ") # Split by space
print(f"Split by space: {words}")

# 7. Joining a list of strings into a single string
joined_words = "-".join(["Python", "is", "awesome"])
print(f"Join with hyphen: '{joined_words}'")

print("n--- Search & Clean-up Methods ---")
# 8. Finding a substring (returns index or -1 if not found)
find_index = message.find("Python")
print(f"Find 'Python' at index: {find_index}")
not_found = message.find("Java")
print(f"Find 'Java' (not found): {not_found}") # -1 means not found

# 9. Stripping whitespace from start/end
stripped_message = message.strip()
print(f"Stripped whitespace: '{stripped_message}'")
```

Output example:
```
--- String Basics ---
Original message: ' Hello Python Learners! Keep Coding! '
Length of message: 39
Concatenation: Good morning, Alice!
Slicing (first word 'Hello'): 'Hello'
Slicing (from index 20): 'Keep Coding! '
Reversed message: ' !gnidoC peeK !srenraeL nohtyP olleH '

--- Transformation Methods ---
Uppercase: ' HELLO PYTHON LEARNERS! KEEP CODING! '
Lowercase: ' hello python learners! keep coding! '
Replace 'Coding' with 'Learning': ' Hello Python Learners! Keep Learning! '
Split by space: ['Python', 'is', 'super', 'fun']
Join with hyphen: 'Python-is-awesome'

--- Search & Clean-up Methods ---
Find 'Python' at index: 9
Find 'Java' (not found): -1
Stripped whitespace: 'Hello Python Learners! Keep Coding!'
```

💡 **Your Challenge:**
Create a string with a messy email address like ` " My.Email@EXAMPLE.com " `.
Then, use string methods to:
1. Remove all leading/trailing whitespace.
2. Convert the entire email to lowercase.
3. Replace ".com" with ".org".
Print the final cleaned and modified email! 📧

---
Day 9: String Manipulation \- Code & Output
What will be the output of the following Python code?

text = "apple,banana,cherry" parts = text.split(',') result = "-".join(parts) print(result)
Anonymous Quiz
0%
['apple', 'banana', 'cherry']
0%
apple-banana-cherry
0%
apple,banana,cherry
0%
apple,banana,cherry-
Hello Python learners! 👋 On Day 10, we're diving into *File I/O* (Input/Output)! 📂 This essential skill allows your programs to read data from files and write results back to them, making your data persistent. No more losing info when your script ends! We'll cover opening files, basic modes (`'r'` for read, `'w'` for write), and the golden rule: using `with open(...)` for safe file handling. Let's make our Python scripts remember things! ✨

```python
# Define a filename
my_file = "learning_log.txt"

# --- Part 1: Writing to a file ---
print(f"Creating and writing to '{my_file}'...")
with open(my_file, "w") as f: # 'w' mode (write) will create or overwrite
f.write("Day 10: File I/O session.n")
f.write("We are learning to persist data!n")
f.write("This line was added using Python's write() method. 👋n")
print(f"Successfully wrote data to '{my_file}'.")

# --- Part 2: Reading from a file ---
print(f"nReading content from '{my_file}'...")
with open(my_file, "r") as f: # 'r' mode (read)
file_content = f.read() # Reads the entire file content
print("--- File Content Start ---")
print(file_content)
print("--- File Content End ---")
print(f"Successfully read data from '{my_file}'.")
```

Output example:
```
Creating and writing to 'learning_log.txt'...
Successfully wrote data to 'learning_log.txt'.

Reading content from 'learning_log.txt'...
--- File Content Start ---
Day 10: File I/O session.
We are learning to persist data!
This line was added using Python's write() method. 👋

--- File Content End ---
Successfully read data from 'learning_log.txt'.
```

Challenge Time! 🚀 Modify the code to *append* a new line of text to `learning_log.txt` without overwriting the existing content. Then, read the *entire* file again to see the updated content! (Hint: Think about file modes!)

---
Day 10: File I/O \(Input/Output\) \- Code & Output
Which file mode should you use to add new content to an existing file without deleting its original content?
Anonymous Quiz
0%
'w'
0%
'r'
0%
'a'
0%
'x'
Alright, Python explorers! 🚀 Get ready to build more robust and user-friendly applications!

---

### **Day 11: Error Handling (try, except)**

Ever had your Python script crash unexpectedly? 🐛 Today, we tackle how to gracefully handle those hiccups! With `try` and `except` blocks, you can anticipate potential errors, prevent your program from stopping abruptly, and provide meaningful feedback to users. It's like giving your code a safety net! 🛠️ Let's dive into making your programs more resilient!

```python
print("--- Day 11: Error Handling (try, except) ---")

try:
num1_str = input("Enter the first number: ")
num2_str = input("Enter the second number: ")

num1 = int(num1_str) # This might raise ValueError
num2 = int(num2_str) # This might raise ValueError

result = num1 / num2 # This might raise ZeroDivisionError
print(f"The result of {num1} / {num2} is: {result}")

except ValueError:
# Catches errors when conversion to int fails (e.g., input is 'abc')
print("Oops! 🛑 Invalid input. Please enter whole numbers only.")
except ZeroDivisionError:
# Catches errors when attempting to divide by zero
print("Error! 🚫 Cannot divide by zero. Please enter a non-zero second number.")
except Exception as e:
# A generic catch-all for any other unexpected errors
print(f"An unexpected error occurred: {e}")
finally:
# This block always executes, regardless of whether an exception occurred or not
print("Error handling check complete. ✨")

print("Program continues its execution. 🎉")
```

Output example (if you enter `10` and `0`):
```
--- Day 11: Error Handling (try, except) ---
Enter the first number: 10
Enter the second number: 0
Error! 🚫 Cannot divide by zero. Please enter a non-zero second number.
Error handling check complete. ✨
Program continues its execution. 🎉
```

---

### **Small Challenge:**
Can you modify the code above to keep asking the user for input (in a loop) until two *valid* numbers are entered and a successful division operation can be performed? 🤔 (Hint: Think `while` loop!)

---
Day 11: Error Handling \(try, except\) \- Code Example