Python Tutorial Day 5
Python Tutorial Day 5
Association Associated with the class object. Not associated with any objects.
Dependenc It depends on the class they belong It doesn’t depend on any class, i.e., it is
y to. an identical entity.
self It requires the self as its first It doesn’t require any self-argument.
argument.
operation It operates on the data of the object It operates on the data that you pass to
it associates with. them as an argument.
print(f"{greeting}, {name}!")
greet("Alice", greeting="Hi")
# Output: Hi, Alice!
In this example, name and greeting are parameters, and "Alice" and "Hi" are arguments
Positional parameters are the most common type in Python. They are defined in the order in
which they appear in the function or method signature.
result = a + b
add_numbers(5, 7)
Keyword parameters allow you to specify arguments by name, providing clarity and flexibility in
function calls.
4. Default Values
Default values for parameters allow you to define optional arguments with pre-assigned values.
print(f"{greeting}, {name}!")
5. Variable-Length Parameters
The *args syntax collects positional arguments into a tuple within the function.
def print_items(*items):
for item in items:
print(item)
print_items(1, 2, 3)
# Output: 1 \n 2 \n 3
def print_properties(**properties):
print(f"{key}: {value}")
The **kwargs syntax collects keyword arguments into a dictionary within the function.
Positional-only parameters are specified using the / symbol. Parameters before / must be
passed by position.
# Example of a function with positional-only parameters
return x + y + z
result = positional_only_example(1, 4, 6)
print(result) # Output: 11
In this example, x is a positional-only parameter, and y and z can be either positional or keyword
arguments.
Keyword-only parameters are specified using the * symbol. Parameters after * must be passed
by name.
python
Copy code
return a + b + c + d
print(result) # Output: 10
In this example, c and d are keyword-only parameters, and they must be passed using keyword
arguments.
python
Copy code
total = a + b + c + d
total += arg
total += value
return total
print(result) # Output: 28
python
Copy code
class MyClass:
return a + b + c
my_instance = MyClass()
print(result) # Output: 6
In this example, example_method is a class method that can be called on an instance of the
class.
python
Copy code
pass
Avoid using reserved keywords (e.g., def, if, else) as parameter names.
class Dog:
self.name = name
self.age = age
my_dog.bark(times=2)
python
Copy code
class Calculator:
self.value = value
def add(self, x):
self.value += x
self.value *= y
my_calculator = Calculator(value=2)
result = my_calculator.add(3).multiply(4).value
print(result) # Output: 20
In this example, the Calculator class demonstrates method chaining, where each method
modifies the object's state and returns self, allowing for consecutive method calls.
class MathOperations:
@classmethod
Class methods, denoted by @classmethod, can be called on the class itself. In this example,
the power class method calculates and prints the power of a number.
class StringUtils:
@staticmethod
def is_palindrome(word):
result = StringUtils.is_palindrome(word="level")
Static methods, denoted by @staticmethod, don't have access to the instance or class. They
are useful for utility functions, as shown in this example with a palindrome checker.
python
Copy code
class MyClass:
self.instance_variable = instance_variable
result = self.instance_variable + x
@classmethod
result = cls.class_variable * y
my_instance = MyClass(instance_variable=5)
my_instance.instance_method(x=3)
MyClass.class_method(y=2)
This example illustrates a class with both instance and class methods. Instance methods
operate on the instance's data, while class methods can access and modify class-level
attributes.
Example: Default Values and Keyword Arguments
python
Copy code
class Rectangle:
self.length = length
self.width = width
def calculate_area(self):
default_rectangle = Rectangle()
area_default = default_rectangle.calculate_area()
area_custom = custom_rectangle.calculate_area()
In this example, the Rectangle class has an __init__ method with default values for length and
width. The calculate_area method is then called on instances with both default and custom
values.
python
Copy code
class ShoppingCart:
self.items = items
def display_items(self):
print(f"- {item}")
cart1.display_items()
# Output:
# - Apple
# - Banana
# - Orange
cart2.display_items()
# Output:
# - Laptop
# - Mouse
# - Keyboard
# - Headphones
Here, the ShoppingCart class accepts variable-length positional arguments using *items in the
constructor, allowing for flexibility in the number of items passed to each instance.
python
Copy code
class Student:
self.name = name
self.details = details
def display_info(self):
print("Additional Details:")
student1.display_info()
# Output:
# Additional Details:
# - age: 22
# - grade: A
student2.display_info()
# Output:
# Additional Details:
# - age: 20
# - GPA: 3.8
In this example, the Student class uses **details to accept variable-length keyword arguments,
allowing the addition of various details for each student.
Python Slicing
Lists: A
Comprehensive
Tutorial
1. Introduction to List Slicing
List slicing is a technique that allows you to extract a portion of a list by specifying the start and
stop indices. It provides a concise and efficient way to work with subsets of data within a list.
python
Copy code
new_list = original_list[start:stop:step]
python
Copy code
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
result = numbers[2:7]
python
Copy code
result = numbers[:5]
result = numbers[5:]
python
Copy code
# Slicing the last three elements using negative indices
result = numbers[-3:]
result = numbers[-6:-2]
python
Copy code
result = numbers[1:8:2]
result = numbers[::-1]
python
Copy code
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
result = matrix[1]
python
Copy code
result = matrix[2][1]
print(result) # Output: 8
python
Copy code
result = numbers[:3]
python
Copy code
result = numbers[::2]
6. Slicing Strings
python
Copy code
result = text[:6]
result = text[::3]
python
Copy code
# Reversing a string using slicing
result = text[::-1]
python
Copy code
python
Copy code
del numbers[1:4]
python
Copy code
result = numbers[None:7]
python
Copy code
my_slice = slice(2, 8, 2)
result = numbers[my_slice]
python
Copy code
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
odd_numbers = numbers[1::2]
even_numbers = numbers[::2]
reversed_groups = numbers[::3][::-1]
print(reversed_groups) # Output: [6, 5, 4, 3, 2, 1, 0]
In this example, we demonstrate the flexibility of list slicing by extracting odd and even numbers
and reversing every second group of three numbers.
python
Copy code
print(colors)
colors[-2:] = []
print(colors)
Here, we showcase how list slicing enables us to modify specific portions of a list, including
replacing and removing elements.
python
Copy code
# Slicing a 2D list for a specific column
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
This example demonstrates slicing in the context of a 2D list, extracting a specific column from
the matrix.
python
Copy code
In this example, we combine list slicing with list comprehension to filter elements based on
certain conditions.
python
Copy code
even_chars = text[::2]
reversed_text = text[::-1]
In Python, break and continue are control flow statements used in loops to alter their normal
execution. These statements are especially useful in situations where you want to modify the
flow of a loop based on specific conditions.
if number == 5:
break
print(number)
for i in range(5):
for j in range(5):
if i == j == 3:
break
print(i, j)
python
Copy code
if number % 2 == 0:
continue
print(number)
python
Copy code
for i in range(3):
for j in range(3):
if i == j:
print(i, j)
Searching for an Element: Use break when you find the target element.
Avoiding Deep Nesting: Excessive use of break and continue can lead to less readable code.
python
Copy code
if char == "h":
break
if char == "t":
print("Skipping 't'")
continue
print(char)
Copy code
count = 0
if count == 2:
break
print(count)
count += 1
Searching for a Value: Use break when the target value is found.
python
Copy code
found = False
if is_condition_met(item):
found = True
break
# The rest of the code that depends on 'found' variable
if found:
process_item(item)
else:
handle_not_found()
python
Copy code
outer_loop = False
for i in range(5):
for j in range(5):
if i == j == 3:
outer_loop = True
break
print(i, j)
if outer_loop:
break
python
Copy code
if number == 11:
break
print(number)
else:
9. Additional Examples
python
Copy code
target_element = 7
numbers = [3, 5, 1, 7, 2, 8, 7, 6]
if number == target_element:
print(f"Found {target_element}!")
break
print(number)
In this example, the loop breaks as soon as it finds the first occurrence of the target element.
python
Copy code
for i in range(10):
if i % 2 == 0:
continue
print(i)
Here, continue is used to skip even numbers, resulting in a printout of only odd numbers.
python
Copy code
threshold = 5
numbers = [2, 8, 1, 7, 5, 3, 9]
break
print(number)
In this example, the loop breaks when it encounters a number greater than the dynamically set
threshold.
python
Copy code
if item == "banana":
continue
print(f"Processing {item}")
python
Copy code
outer_loop = False
for i in range(5):
for j in range(5):
if i == j == 3:
outer_loop = True
break
print(i, j)
if outer_loop:
break
This example demonstrates using a label and break to exit an outer loop when a certain
condition is met within the inner loop.
python
Copy code
target_number = 11
if number == target_number:
break
print(number)
else:
Here, the else block is executed only if the loop completes without encountering a break
statement, indicating that the target number was not found.
Python pass
Keyword: A
Comprehensive
Tutorial
Overview of the pass Keyword
In Python, pass is a special keyword that serves as a placeholder. It doesn't perform any action
and is often used when syntactically some code is required but no meaningful operation is
desired.
python
Copy code
if condition:
Copy code
def my_function():
class MyClass:
python
Copy code
if some_condition:
else:
python
Copy code
# Using pass with other statements
if condition:
print("Condition is met")
else:
python
Copy code
try:
result = 10 / 0
except ZeroDivisionError:
python
Copy code
try:
except ValueError:
5. pass in Loops
python
Copy code
python
Copy code
while some_condition:
6. pass in Classes
python
Copy code
class AnotherClass:
def my_method(self):
python
Copy code
class MyImplementation:
def my_method(self):
python
Copy code
def download_data(url):
python
Copy code
class MyLibrary:
def feature1(self):
# Implementation of feature 1
pass
def feature2(self):
# Implementation of feature 2
pass
python
Copy code
def my_decorator(func):
python
Copy code
else: