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:
---
🐍 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:
Which of the following statements about Python lists and tuples is true?
Anonymous Quiz
100%
A) Lists are immutable, while tuples are mutable.
0%
B) Both lists and tuples are mutable.
0%
C) Lists are mutable, while tuples are immutable.
0%
D) Both lists and tuples are immutable.
Which of the following is TRUE about Python dictionaries and sets?
Anonymous Quiz
0%
Dictionary keys must be unique and immutable; set elements must be unique and immutable.
100%
Dictionary keys must be unique but can be mutable; set elements must be unique but can be mutable.
0%
Dictionary keys can be duplicated; set elements must be unique and immutable.
0%
Both dictionary keys and set elements can be duplicated.
🚀 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! 📧
---
```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! 📧
---
What will be the output of the following Python code?
text = "apple,banana,cherry" parts = text.split(',') result = "-".join(parts) print(result)
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!)
---
```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!)
---
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)**
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!)
---
Hey Python Learners! 👋 Ready for Day 12? Today we're unlocking the power of **Modules and Packages**! 📦 These are essential for writing clean, organized, and reusable Python code. Think of modules as single files of Python code you can import, and packages as directories that group related modules together. This makes your projects much more manageable and professional. Let's learn how to structure our code like a pro! 🚀
---
```python
# --- File: math_operations.py ---
# This is a simple module
def add(a, b):
"""Returns the sum of two numbers."""
return a + b
def subtract(a, b):
"""Returns the difference of two numbers."""
return a - b
if __name__ == "__main__":
print(f"Running math_operations directly. 5 + 3 = {add(5, 3)}")
# --- File: my_package/__init__.py ---
# This empty file tells Python that 'my_package' is a package.
# --- File: my_package/string_utils.py ---
# This is a module inside 'my_package'
def reverse_string(s):
"""Reverses a given string."""
return s[::-1]
def capitalize_first(s):
"""Capitalizes the first letter of a string."""
return s.capitalize()
# --- File: main.py ---
# This script will use our module and package
# Make sure math_operations.py and the 'my_package' directory are in the same directory as main.py
import math_operations
from my_package import string_utils
print("--- Using math_operations module ---")
result_add = math_operations.add(10, 5)
print(f"10 + 5 = {result_add}")
result_sub = math_operations.subtract(10, 5)
print(f"10 - 5 = {result_sub}")
print("n--- Using my_package/string_utils module ---")
original_str = "hello python"
reversed_str = string_utils.reverse_string(original_str)
print(f"'{original_str}' reversed is: '{reversed_str}'")
capitalized_str = string_utils.capitalize_first(original_str)
print(f"'{original_str}' capitalized first is: '{capitalized_str}'")
```
---
Output example:
```
--- Using math_operations module ---
10 + 5 = 15
10 - 5 = 5
--- Using my_package/string_utils module ---
'hello python' reversed is: 'nohtyp olleh'
'hello python' capitalized first is: 'Hello python'
```
---
💡 Challenge Time!
Create a new module called `time_utils.py` with a function `get_current_datetime()` that returns the current date and time (you'll need the `datetime` module!). Then, import `time_utils` into `main.py` and call your new function, printing its result. Share your solution in the comments! 👇
---
---
```python
# --- File: math_operations.py ---
# This is a simple module
def add(a, b):
"""Returns the sum of two numbers."""
return a + b
def subtract(a, b):
"""Returns the difference of two numbers."""
return a - b
if __name__ == "__main__":
print(f"Running math_operations directly. 5 + 3 = {add(5, 3)}")
# --- File: my_package/__init__.py ---
# This empty file tells Python that 'my_package' is a package.
# --- File: my_package/string_utils.py ---
# This is a module inside 'my_package'
def reverse_string(s):
"""Reverses a given string."""
return s[::-1]
def capitalize_first(s):
"""Capitalizes the first letter of a string."""
return s.capitalize()
# --- File: main.py ---
# This script will use our module and package
# Make sure math_operations.py and the 'my_package' directory are in the same directory as main.py
import math_operations
from my_package import string_utils
print("--- Using math_operations module ---")
result_add = math_operations.add(10, 5)
print(f"10 + 5 = {result_add}")
result_sub = math_operations.subtract(10, 5)
print(f"10 - 5 = {result_sub}")
print("n--- Using my_package/string_utils module ---")
original_str = "hello python"
reversed_str = string_utils.reverse_string(original_str)
print(f"'{original_str}' reversed is: '{reversed_str}'")
capitalized_str = string_utils.capitalize_first(original_str)
print(f"'{original_str}' capitalized first is: '{capitalized_str}'")
```
---
Output example:
```
--- Using math_operations module ---
10 + 5 = 15
10 - 5 = 5
--- Using my_package/string_utils module ---
'hello python' reversed is: 'nohtyp olleh'
'hello python' capitalized first is: 'Hello python'
```
---
💡 Challenge Time!
Create a new module called `time_utils.py` with a function `get_current_datetime()` that returns the current date and time (you'll need the `datetime` module!). Then, import `time_utils` into `main.py` and call your new function, printing its result. Share your solution in the comments! 👇
---
What is the primary purpose of an `__init__.py` file within a Python package?
Anonymous Quiz
0%
It defines the main function to be executed when the package is run.
0%
It indicates to Python that the directory should be treated as a package.
0%
It automatically imports all modules within the package.
0%
It stores package-wide variables and constants.
👋 Hey Python learners! Day 13 is here, and we're diving into one of the most powerful concepts: **Object-Oriented Programming (OOP)!** 🏗️ Today, we'll demystify **Classes and Objects**.
Think of a Class as a blueprint (like for a house 🏡), and an Object as a real-world item built from that blueprint (the actual house!). It's how we build structured, organized, and reusable code. Get ready to create your own custom data types! ✨ Let's build some objects!
```python
class Car:
# The __init__ method is called automatically when a new object is created
def __init__(self, make, model, year):
self.make = make # Assigning 'make' to the object's attribute
self.model = model # Assigning 'model' to the object's attribute
self.year = year # Assigning 'year' to the object's attribute
print(f"A new {self.year} {self.make} {self.model} has been created!")
# A method is a function that belongs to an object
def display_info(self):
return f"Car details: {self.year} {self.make} {self.model}"
# Creating objects (instances) of the Car class
my_car = Car("Toyota", "Camry", 2022)
your_car = Car("Honda", "Civic", 2023)
# Accessing attributes and calling methods for our objects
print(my_car.display_info())
print(f"My car's make: {my_car.make}")
print(your_car.display_info())
print(f"Your car's model: {your_car.model}")
```
Output example:
```
A new 2022 Toyota Camry has been created!
A new 2023 Honda Civic has been created!
Car details: 2022 Toyota Camry
My car's make: Toyota
Car details: 2023 Honda Civic
Your car's model: Civic
```
🚀 **Your Challenge:** Can you add a new method called `honk()` to our `Car` class that simply prints 'Beep! Beep!'? Then, call this new method for both `my_car` and `your_car`! Show us your modified code! 👇
---
Think of a Class as a blueprint (like for a house 🏡), and an Object as a real-world item built from that blueprint (the actual house!). It's how we build structured, organized, and reusable code. Get ready to create your own custom data types! ✨ Let's build some objects!
```python
class Car:
# The __init__ method is called automatically when a new object is created
def __init__(self, make, model, year):
self.make = make # Assigning 'make' to the object's attribute
self.model = model # Assigning 'model' to the object's attribute
self.year = year # Assigning 'year' to the object's attribute
print(f"A new {self.year} {self.make} {self.model} has been created!")
# A method is a function that belongs to an object
def display_info(self):
return f"Car details: {self.year} {self.make} {self.model}"
# Creating objects (instances) of the Car class
my_car = Car("Toyota", "Camry", 2022)
your_car = Car("Honda", "Civic", 2023)
# Accessing attributes and calling methods for our objects
print(my_car.display_info())
print(f"My car's make: {my_car.make}")
print(your_car.display_info())
print(f"Your car's model: {your_car.model}")
```
Output example:
```
A new 2022 Toyota Camry has been created!
A new 2023 Honda Civic has been created!
Car details: 2022 Toyota Camry
My car's make: Toyota
Car details: 2023 Honda Civic
Your car's model: Civic
```
🚀 **Your Challenge:** Can you add a new method called `honk()` to our `Car` class that simply prints 'Beep! Beep!'? Then, call this new method for both `my_car` and `your_car`! Show us your modified code! 👇
---
What is the primary purpose of the `__init__` method in a Python class?
Anonymous Quiz
0%
To define class-level variables that are shared by all objects.
0%
To initialize the attributes (state) of a newly created object.
0%
To delete an object from memory once it's no longer needed.
0%
To return a string representation of the object for debugging.
🚀 Day 14: Unlocking the power of Object-Oriented Programming with **Inheritance and Polymorphism**! 🧬 These aren't just fancy words; they're fundamental concepts that let you write incredibly reusable, flexible, and maintainable code.
Inheritance allows you to create new classes (child classes) that build upon existing ones (parent classes), inheriting their attributes and methods. Polymorphism, on the other hand, enables objects of different classes to be treated uniformly through a common interface. Let's see them in action! ✨
```python
# --- Inheritance Example ---
class Animal:
def __init__(self, name):
self.name = name
def make_sound(self):
return f"{self.name} makes a generic sound."
class Dog(Animal): # Dog inherits from Animal
def make_sound(self): # Method overriding
return f"{self.name} barks loudly!"
class Cat(Animal): # Cat inherits from Animal
def make_sound(self): # Method overriding
return f"{self.name} purrs softly."
# --- Polymorphism Example ---
def animal_party(animals):
"""
This function demonstrates polymorphism:
it can work with any object that has a 'make_sound' method,
regardless of its specific class (Dog, Cat, or Animal).
"""
for animal in animals:
print(animal.make_sound())
# Create objects
generic_animal = Animal("Creature")
doggy = Dog("Buddy")
kitty = Cat("Whiskers")
print("--- Demonstrating Inheritance and Overriding ---")
print(generic_animal.make_sound())
print(doggy.make_sound())
print(kitty.make_sound())
print("n--- Demonstrating Polymorphism ---")
zoo_animals = [doggy, kitty, generic_animal]
animal_party(zoo_animals) # All objects respond to make_sound() in their own way
```
Output example:
```
--- Demonstrating Inheritance and Overriding ---
Creature makes a generic sound.
Buddy barks loudly!
Whiskers purrs softly.
--- Demonstrating Polymorphism ---
Buddy barks loudly!
Whiskers purrs softly.
Creature makes a generic sound.
```
💡 **Challenge:** Create a new class `Lion` that inherits from `Animal`. Make it override `make_sound` to return "roars mightily!". Then, add a `Lion` object to the `zoo_animals` list and call `animal_party` again. See the mighty roar! 🦁
---
Inheritance allows you to create new classes (child classes) that build upon existing ones (parent classes), inheriting their attributes and methods. Polymorphism, on the other hand, enables objects of different classes to be treated uniformly through a common interface. Let's see them in action! ✨
```python
# --- Inheritance Example ---
class Animal:
def __init__(self, name):
self.name = name
def make_sound(self):
return f"{self.name} makes a generic sound."
class Dog(Animal): # Dog inherits from Animal
def make_sound(self): # Method overriding
return f"{self.name} barks loudly!"
class Cat(Animal): # Cat inherits from Animal
def make_sound(self): # Method overriding
return f"{self.name} purrs softly."
# --- Polymorphism Example ---
def animal_party(animals):
"""
This function demonstrates polymorphism:
it can work with any object that has a 'make_sound' method,
regardless of its specific class (Dog, Cat, or Animal).
"""
for animal in animals:
print(animal.make_sound())
# Create objects
generic_animal = Animal("Creature")
doggy = Dog("Buddy")
kitty = Cat("Whiskers")
print("--- Demonstrating Inheritance and Overriding ---")
print(generic_animal.make_sound())
print(doggy.make_sound())
print(kitty.make_sound())
print("n--- Demonstrating Polymorphism ---")
zoo_animals = [doggy, kitty, generic_animal]
animal_party(zoo_animals) # All objects respond to make_sound() in their own way
```
Output example:
```
--- Demonstrating Inheritance and Overriding ---
Creature makes a generic sound.
Buddy barks loudly!
Whiskers purrs softly.
--- Demonstrating Polymorphism ---
Buddy barks loudly!
Whiskers purrs softly.
Creature makes a generic sound.
```
💡 **Challenge:** Create a new class `Lion` that inherits from `Animal`. Make it override `make_sound` to return "roars mightily!". Then, add a `Lion` object to the `zoo_animals` list and call `animal_party` again. See the mighty roar! 🦁
---