Class & Function

 In Python, a class is a blueprint for creating objects, which are instances of the class. A class defines the attributes (variables) and methods (functions) that an object will have. You can think of a class as a template or a set of instructions for creating objects.

Here is an example of a class in Python:

python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")

In this example, we define a class called Person. The class has two attributes: name and age. It also has a method called say_hello, which prints out a message introducing the person. The __init__ method is a special method that is called when a new object of the class is created. It sets the initial values of the name and age attributes.

Import statement

Import statement: Used to import modules or packages in Python. The import statement in Python is used to include modules, libraries or packages in a Python program. A module is a file containing Python code, while a package is a collection of modules that are grouped together in a directory.

Here is an example of using the import statement to include the math module in a Python program:

lua
import math

# Use the math module to calculate the square root of 16
result = math.sqrt(16)

print(result)

In this example, we use the import statement to include the math module in our program. We then call the sqrt function from the math module to calculate the square root of 16, and assign the result to a variable called result. Finally, we print out the value of result, which is 4.0.

You can also use the from keyword with the import statement to import specific functions, classes, or variables from a module. For example, here's how to import the sqrt function from the math module using the from keyword:

lua
from math import sqrt

# Use the sqrt function directly
result = sqrt(16)

print(result)

In this example, we use the from keyword with the import statement to import only the sqrt function from the math module. We can then call the sqrt function directly, without having to prefix it with the math. namespace. This can make the code shorter and easier to read.

Object

Object: An instance of a class that contains data and methods defined in the class. In Python, an object is an instance of a class that has its own identity, attributes (variables), and methods (functions). An object is created from a class using the class_name() syntax, which invokes the class's constructor method.

Here is an example of creating an object in Python:

python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")

# Create a Person object
person1 = Person("Alice", 30)

# Call the say_hello method on the Person object
person1.say_hello()

In this example, we define a Person class with an __init__ constructor method and a say_hello method. We then create a Person object called person1 by invoking the Person class with the arguments "Alice" and 30. Finally, we call the say_hello method on person1, which prints out a message introducing the person:

python
Hello, my name is Alice and I am 30 years old.

When we create an object in Python, it has its own unique identity, which is determined by its memory address. We can use the built-in id() function to get the identity of an object:

scss
person2 = Person("Bob", 25)

print(id(person1))
print(id(person2))

In this example, we create a second Person object called person2 with the arguments "Bob" and 25. We then print out the identities of person1 and person2 using the id() function. The output might look something like this:

140489979554864
140489979554840

Note that the identities of the two objects are different, even though they are both instances of the same class. This is because each object has its own unique memory address in the computer's memory.

Module

Module: A file containing Python definitions and statements that can be used in other Python programs. In Python, a module is a file containing Python code, usually containing functions, classes, and other definitions that can be imported and used in other Python programs.

Here is an example of creating a simple Python module:

my_module.py

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

def add_numbers(x, y):
return x + y

In this example, we define a Python module called my_module.py that contains two functions: greet() and add_numbers(). The greet() function takes a name as an argument and prints out a greeting message, while the add_numbers() function takes two numbers as arguments and returns their sum.

To use this module in another Python program, we can use the import statement:

my_program.py

sql
import my_module

# Call the greet function from my_module
my_module.greet("Alice")

# Call the add_numbers function from my_module
result = my_module.add_numbers(3, 4)

print(result)

In this example, we import the my_module module using the import statement. We can then call the greet() and add_numbers() functions from the my_module module by prefixing them with the module name and a dot. Finally, we print out the result of calling the add_numbers() function.

Alternatively, we can use the from keyword to import specific functions from a module:

my_program.py

sql
from my_module import greet, add_numbers

# Call the greet function directly
greet("Bob")

# Call the add_numbers function directly
result = add_numbers(5, 6)

print(result)

In this example, we use the from keyword to import the greet and add_numbers functions directly from the my_module module. We can then call the functions directly without prefixing them with the module name and a dot.

Package

Package: A collection of modules that can be used in other Python programs. In Python, a package is a collection of related modules that are organized into a directory hierarchy. A package directory must contain an __init__.py file, which can be empty or contain initialization code for the package.

Here is an example of creating a simple Python package:

markdown
my_package/
__init__.py
greet.py
math/
__init__.py
add.py

In this example, we create a package called my_package that contains two modules: greet.py and math. The math module contains a sub-module called add.py. The __init__.py files are empty in this example, but they are required to make the directories they are in Python packages.

Here's an example of what the contents of greet.py and add.py might look like:

greet.py

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

add.py

python
def add_numbers(x, y):
return x + y

We can use the import statement to use functions from the package and its modules:

wasm
import my_package.greet
import my_package.math.add

my_package.greet.say_hello("Alice")

result = my_package.math.add.add_numbers(3, 4)

print(result)

In this example, we use the import statement to import the say_hello() function from the greet module and the add_numbers() function from the add module within the math sub-package. We can then call the functions using the module name and function name separated by a dot.

Alternatively, we can use the from keyword to import specific functions from the package and its modules:

python
from my_package.greet import say_hello
from my_package.math.add import add_numbers

say_hello("Bob")

result = add_numbers(5, 6)

print(result)

In this example, we use the from keyword to import the say_hello() and add_numbers() functions directly. We can then call the functions directly without prefixing them with the module names and dots.

Argument

Argument: A value passed to a function or method when it is called. In Python, an argument is a value that is passed to a function or method when it is called. Arguments are used to provide input data to the function or method and can be of different types, such as integers, strings, lists, dictionaries, and objects.

Here is an example of a function that takes two arguments:

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

greet("Alice", "Hello")

In this example, we define a function called greet() that takes two arguments: name and greeting. The function prints out a greeting message that includes the name and the greeting. We then call the function with two arguments: "Alice" for the name parameter and "Hello" for the greeting parameter.

The output of this program would be:

Hello, Alice!

Functions can also have default values for their arguments, which are used if no value is provided when the function is called:

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

greet("Alice")
greet("Bob", "Hi")

In this example, we define a function called greet() that takes two arguments: name and greeting, with a default value of "Hello" for the greeting parameter. We then call the function twice, once with only the name argument and once with both arguments.

The output of this program would be:

Hello, Alice!
Hi, Bob!

We can also pass arguments to functions using keyword arguments, where we specify the name of the parameter and its value explicitly:

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

greet(name="Alice", greeting="Hello")

In this example, we call the greet() function with two keyword arguments: "Alice" for the name parameter and "Hello" for the greeting parameter. The order of the arguments doesn't matter when using keyword arguments.

Parameter

Parameter: A variable used in a function or method to accept an argument. In Python, a parameter is a variable in a function definition that represents an argument passed to the function when it is called. Parameters are used to define the input requirements for the function and provide a way to access the values of the arguments within the function body.

Here is an example of a function that takes two parameters:

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

greet("Alice", "Hello")

In this example, we define a function called greet() that takes two parameters: name and greeting. The function prints out a greeting message that includes the name and the greeting. When we call the function with two arguments, Python assigns the first argument to the name parameter and the second argument to the greeting parameter.

We can also define default values for parameters, which are used if no value is provided when the function is called:

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

greet("Alice")
greet("Bob", "Hi")

In this example, we define a function called greet() that takes two parameters: name and greeting, with a default value of "Hello" for the greeting parameter. When we call the function with only one argument, Python uses the default value for the greeting parameter. When we call the function with two arguments, Python assigns the first argument to the name parameter and the second argument to the greeting parameter.

We can also use keyword arguments to specify the values of parameters explicitly when calling a function:

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

greet(name="Alice", greeting="Hello")

In this example, we call the greet() function with two keyword arguments: "Alice" for the name parameter and "Hello" for the greeting parameter. The order of the arguments doesn't matter when using keyword arguments.

Parameters allow us to create flexible and reusable functions that can be customized for different use cases by passing different arguments.

Exception

Exception: An error that occurs during the execution of a program that disrupts the normal flow of the program. In Python, an exception is an error that occurs during the execution of a program. Exceptions are raised when the interpreter encounters an error that it cannot recover from, such as a syntax error or a runtime error. Python provides a way to handle exceptions using a try-except block, which allows us to catch and handle exceptions gracefully instead of crashing the program.

Here is an example of a try-except block that handles a runtime exception:

python
try:
x = 1 / 0
except ZeroDivisionError:
print("Error: division by zero")

In this example, we use a try-except block to handle the ZeroDivisionError exception that occurs when we try to divide a number by zero. The code in the try block raises the exception by dividing the number 1 by 0, which is not allowed in Python. The except block catches the exception and prints out an error message.

We can also use a try-except block to catch multiple exceptions:

python
try:
x = int("not a number")
except ValueError:
print("Error: invalid literal for int() with base 10")
except TypeError:
print("Error: wrong type for int() function")

In this example, we use a try-except block to handle two exceptions that can occur when we try to convert a string to an integer using the int() function. The ValueError exception is raised when the string is not a valid integer literal, and the TypeError exception is raised when the argument is not a string.

We can also use a try-except-else block to run some code if no exception is raised:

python
try:
x = 1 / 2
except ZeroDivisionError:
print("Error: division by zero")
else:
print("No error occurred")

In this example, we use a try-except-else block to handle the ZeroDivisionError exception that occurs when we try to divide a number by zero. If no exception is raised, the code in the else block is executed.

Exceptions allow us to write more robust and reliable programs by handling errors gracefully and providing informative error messages to users.

Slice

Slice: A subset of a sequence (e.g., a string or list) defined by a range of indices. In Python, a slice is a way to extract a portion of a sequence, such as a string, list, or tuple. Slicing allows us to create a new sequence that contains only the elements we're interested in, without modifying the original sequence.

The syntax for slicing a sequence is [start:stop:step], where start is the index of the first element to include, stop is the index of the first element to exclude, and step is the stride between elements.

Here is an example of slicing a string:

python
s = "hello world"
print(s[0:5]) # prints "hello"
print(s[6:]) # prints "world"
print(s[::2]) # prints "hlowrd"

In this example, we define a string s that contains the text "hello world". We use slicing to extract different portions of the string:

  • s[0:5] extracts the characters at indices 0 through 4 (inclusive), which spell out the word "hello".
  • s[6:] extracts all the characters from index 6 to the end of the string, which spell out the word "world".
  • s[::2] extracts every other character from the string, starting at index 0, which spells out "hlowrd".

Here is an example of slicing a list:

scss
l = [1, 2, 3, 4, 5]
print(l[1:3]) # prints [2, 3]
print(l[::2]) # prints [1, 3, 5]

In this example, we define a list l that contains the integers from 1 to 5. We use slicing to extract different portions of the list:

  • l[1:3] extracts the elements at indices 1 and 2 (inclusive), which are the integers 2 and 3.
  • l[::2] extracts every other element from the list, starting at index 0, which are the integers 1, 3, and 5.

Slicing is a powerful tool in Python that allows us to work with sequences more efficiently and effectively. It's especially useful when working with large sequences where we only need to access a subset of the elements



Popular posts from this blog

Series & Dataframe