Data Type in Python:
In Python, data types represent the kind of value a variable can hold. Python is a dynamically typed language, which
means you don't need to explicitly declare the data type of a variable; the interpreter determines the type
dynamically during runtime. Here are some common data types in Python:
1. **Numeric Types:**
- **int:** Integer type (e.g., 1, -5, 1000)
- **float:** Floating-point type (e.g., 3.14, -2.5, 0.0)
```python
# Numeric types
integer_variable = 10
float_variable = 3.14
```
2. **Sequence Types:**
- **str:** String type (e.g., "hello", 'world')
- **list:** List type (e.g., [1, 2, 3], ['a', 'b', 'c'])
- **tuple:** Tuple type (e.g., (1, 2, 3), ('x', 'y', 'z'))
```python
# Sequence types
string_variable = "Hello, World!"
list_variable = [1, 2, 3]
tuple_variable = (4, 5, 6)
```
3. **Set Types:**
- **set:** Set type (e.g., {1, 2, 3}, {'apple', 'orange', 'banana'})
```python
# Set type
set_variable = {1, 2, 3}
```
4. **Mapping Type:**
- **dict:** Dictionary type (e.g., {'key1': 'value1', 'key2': 'value2'})
```python
# Dictionary type
dictionary_variable = {'name': 'John', 'age': 25, 'city': 'New York'}
```
5. **Boolean Type:**
- **bool:** Boolean type (True or False)
```python
# Boolean type
boolean_variable = True
```
6. **None Type:**
- **NoneType:** Represents the absence of a value or a null value.
```python
# None type
none_variable = None
```
7. **Other Types:**
- **complex:** Complex number type (e.g., 1 + 2j)
```python
# Complex number type
complex_variable = 1 + 2j
```
These are the fundamental data types in Python. Additionally, Python supports a wide range of libraries and modules
that introduce more specialized data types for various purposes.
Recursion (Local + Global) in Python:
### Local Recursion:
#### 1. Factorial Calculation:
```python
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n-1)
result = factorial(5)
print(f"The factorial of 5 is: {result}")
```
#### 2. Fibonacci Sequence:
```python
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
for i in range(6):
print(f"Fibonacci({i}) = {fibonacci(i)}")
```
### Global Recursion:
#### 1. Tower of Hanoi:
```python
def tower_of_hanoi(n, source, auxiliary, target):
if n > 0:
# Move n-1 disks from source to auxiliary peg
tower_of_hanoi(n-1, source, target, auxiliary)
# Move the nth disk from source to target peg
print(f"Move disk {n} from {source} to {target}")
# Move the n-1 disks from auxiliary to target peg
tower_of_hanoi(n-1, auxiliary, source, target)
# Example: Move 3 disks from peg A to peg C using peg B as auxiliary
tower_of_hanoi(3, 'A', 'B', 'C')
```
#### 2. Binary Search:
```python
def binary_search(arr, target, low, high):
if low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
return binary_search(arr, target, mid + 1, high)
else:
return binary_search(arr, target, low, mid - 1)
else:
return -1
# Example: Search for 5 in a sorted list
sorted_list = [1, 3, 5, 7, 9, 11, 13, 15]
result = binary_search(sorted_list, 5, 0, len(sorted_list) - 1)
if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found in the list")
```
These examples showcase both local and global recursion in Python. The local recursion is demonstrated by functions
calling themselves, while the global recursion involves multiple functions calling each other in a recursive manner.
Lists in Python:
In Python, the term "array" is often used to refer to lists. A list is a versatile, built-in data structure in Python that can
be used to store an ordered collection of items. Lists can hold elements of different data types and can be modified
after creation. Here's a basic overview of working with arrays (lists) in Python:
### Creating Lists:
You can create a list by enclosing elements in square brackets `[]` and separating them with commas.
```python
my_list = [1, 2, 3, 4, 5]
mixed_list = [1, 'hello', 3.14, True]
empty_list = []
```
### Accessing Elements:
You can access individual elements in a list using index notation. Python uses zero-based indexing.
```python
print(my_list[0]) # Output: 1
print(mixed_list[1]) # Output: 'hello'
```
### Modifying Lists:
Lists are mutable, meaning you can modify their contents.
```python
my_list[2] = 10
print(my_list) # Output: [1, 2, 10, 4, 5]
```
### List Operations:
```python
# Concatenation
new_list = my_list + mixed_list
# Repetition
repeated_list = my_list * 2
# Length
length = len(my_list)
# Check if an element is in the list
is_present = 3 in my_list
```
### List Methods:
Python provides several built-in methods for working with lists:
```python
my_list.append(6) # Add an element to the end
my_list.insert(2, 7) # Insert an element at a specific index
my_list.remove(4) # Remove the first occurrence of a value
popped_value = my_list.pop() # Remove and return the last element
my_list.sort() # Sort the list in ascending order
my_list.reverse() # Reverse the order of elements
```
### Slicing:
You can extract a sublist (slice) from a list using slicing notation.
```python
subset = my_list[1:4] # Elements at index 1, 2, and 3
```
Lists in Python are dynamic and can be modified easily. If you need more advanced features like mathematical
operations on arrays or fixed-size arrays, you might want to explore the `numpy` library, which provides powerful
array manipulation capabilities.
Iteration in Python:
Iteration is a process of repeatedly executing a set of statements or a block of code. In Python, there are several ways
to perform iteration. Here are some common methods:
### 1. **For Loop:**
The `for` loop is used to iterate over a sequence (such as a list, tuple, string, or range).
```python
# Iterate over a list
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
```
```python
# Iterate over a range of numbers
for i in range(1, 5):
print(i)
```
### 2. **While Loop:**
The `while` loop continues to execute a block of code as long as a specified condition is true.
```python
# While loop to print numbers from 1 to 5
i=1
while i <= 5:
print(i)
i += 1
```
### 3. **Iterating Over Elements and Indices:**
You can use the `enumerate` function to iterate over both elements and their indices in a sequence.
```python
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(f"Index: {index}, Fruit: {fruit}")
```
### 4. **Iterating Over Dictionaries:**
You can iterate over the keys, values, or key-value pairs of a dictionary.
```python
person = {'name': 'John', 'age': 30, 'city': 'New York'}
for key, value in person.items():
print(f"{key}: {value}")
```
### 5. **List Comprehensions:**
List comprehensions provide a concise way to create lists and perform iteration in a single line.
```python
squares = [x**2 for x in range(1, 6)]
print(squares) # Output: [1, 4, 9, 16, 25]
```
### 6. **Break and Continue:**
The `break` statement is used to exit a loop prematurely, and the `continue` statement skips the rest of the code
inside the loop for the current iteration.
```python
# Using break
for i in range(1, 10):
if i == 5:
break
print(i)
```
```python
# Using continue
for i in range(1, 6):
if i == 3:
continue
print(i)
```
These are some of the common ways to perform iteration in Python. Depending on the context, you may choose the
most suitable method for your specific requirements.
String in Python:
In Python, a string is a sequence of characters. Strings are one of the fundamental data types and are commonly used
for storing and manipulating textual data. Here are some basic operations and concepts related to strings in Python:
### Creating Strings:
You can create a string by enclosing characters within single (`'`) or double (`"`) quotes.
```python
str1 = 'Hello, World!'
str2 = "Python is fun."
```
### String Operations:
1. **Concatenation:**
```python
concatenated_str = str1 + ' ' + str2
print(concatenated_str)
```
2. **Repetition:**
```python
repeated_str = str1 * 3
print(repeated_str)
```
3. **Indexing:**
Strings are indexed, starting from 0.
```python
first_char = str1[0]
last_char = str1[-1]
```
4. **Slicing:**
You can extract a substring using slicing notation.
```python
substring = str1[0:5] # Characters at index 0, 1, 2, 3, and 4
```
5. **String Length:**
```python
length = len(str1)
```
6. **String Methods:**
Python provides many built-in methods for working with strings.
```python
upper_case = str1.upper()
lower_case = str1.lower()
is_alpha = str1.isalpha()
```
### Escape Characters:
You can use escape characters to include special characters in a string.
```python
escaped_str = "This is a \"quoted\" string."
new_line_str = "This is a line\nbreak."
```
### String Formatting:
String formatting allows you to create dynamic strings.
```python
name = "John"
age = 25
formatted_str = "My name is {} and I'm {} years old.".format(name, age)
```
In Python 3.6 and above, you can use f-strings for a more concise way of formatting:
```python
formatted_str = f"My name is {name} and I'm {age} years old."
```
### String Methods:
Python provides a rich set of methods for string manipulation. Some commonly used methods include:
- `str.upper()`: Converts all characters in the string to uppercase.
- `str.lower()`: Converts all characters in the string to lowercase.
- `str.strip()`: Removes leading and trailing whitespaces.
- `str.split()`: Splits the string into a list of substrings.
- `str.find()`: Returns the index of the first occurrence of a substring.
- `str.replace()`: Replaces a specified substring with another substring.
```python
text = "Hello, world!"
uppercase_text = text.upper()
split_text = text.split(", ")
```
These are just some basics of working with strings in Python. Strings are a versatile and essential part of Python
programming, and there's much more you can do with them.
Inheritance in Python:
Certainly! Here's an example of inheritance in Python with a simple program involving a base class (`Person`) and two
derived classes (`Student` and `Teacher`):
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display_info(self):
return f"Name: {self.name}, Age: {self.age}"
class Student(Person):
def __init__(self, name, age, student_id):
# Call the constructor of the base class
super().__init__(name, age)
self.student_id = student_id
def display_info(self):
# Override the display_info method
return f"Student ID: {self.student_id}, {super().display_info()}"
class Teacher(Person):
def __init__(self, name, age, employee_id):
# Call the constructor of the base class
super().__init__(name, age)
self.employee_id = employee_id
def display_info(self):
# Override the display_info method
return f"Employee ID: {self.employee_id}, {super().display_info()}"
# Create instances of derived classes
student = Student(name="Alice", age=20, student_id="S12345")
teacher = Teacher(name="Mr. Smith", age=35, employee_id="T98765")
# Display information using overridden methods
print(student.display_info())
print(teacher.display_info())
```
In this example:
- `Person` is the base class with common attributes (`name` and `age`) and a method (`display_info`) to display
information.
- `Student` and `Teacher` are derived classes that inherit from the `Person` class. They both have additional attributes
(`student_id` and `employee_id`, respectively) and override the `display_info` method to include their specific
information.
- The `super()` function is used to call the constructor and methods of the base class.
When you run this program, you will see that instances of `Student` and `Teacher` can access both the attributes and
methods of the `Person` class while having their specific attributes and methods.
Encapsulation in python:
Encapsulation is one of the fundamental principles of object-oriented programming, emphasizing the bundling of
data and methods that operate on that data within a single unit, known as a class. Here's an example of
encapsulation in Python:
```python
class Student:
def __init__(self, name, age, student_id):
# Private attributes
self.__name = name
self.__age = age
self.__student_id = student_id
# Public methods to access private attributes
def get_name(self):
return self.__name
def get_age(self):
return self.__age
def get_student_id(self):
return self.__student_id
# Public method to modify private attribute
def set_age(self, new_age):
if 0 < new_age < 120:
self.__age = new_age
else:
print("Invalid age value")
# Display information about the student
def display_info(self):
print(f"Student ID: {self.__student_id}, Name: {self.__name}, Age: {self.__age}")
# Create an instance of the Student class
student1 = Student(name="Alice", age=20, student_id="S12345")
# Accessing attributes using public methods
print("Name:", student1.get_name())
print("Age:", student1.get_age())
print("Student ID:", student1.get_student_id())
# Modifying attribute using public method
student1.set_age(21)
# Display information
student1.display_info()
```
In this example:
- The attributes (`__name`, `__age`, `__student_id`) are encapsulated as they are private and can only be accessed or
modified through public methods (`get_name`, `get_age`, `get_student_id`, `set_age`).
- The `set_age` method ensures that the age is within a valid range before modifying the attribute.
- The `display_info` method provides a way to display information about the student while encapsulating the internal
details of the class.
This encapsulation ensures that the internal state of the `Student` class is protected and can only be accessed or
modified through well-defined interfaces, promoting data integrity and security.
Exception handling in Python:
Exception handling is a crucial aspect of programming to handle runtime errors and unexpected situations. Here are
some Python programs that demonstrate different aspects of exception handling:
### 1. Basic Exception Handling:
```python
try:
x = 10 / 0 # Division by zero
except ZeroDivisionError as e:
print(f"Error: {e}")
else:
print("No exception occurred.")
finally:
print("Finally block always executed.")
```
### 2. Custom Exception:
```python
class CustomError(Exception):
def __init__(self, message):
self.message = message
try:
raise CustomError("This is a custom exception.")
except CustomError as ce:
print(f"Custom Error: {ce.message}")
```
### 3. Handling Multiple Exceptions:
```python
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
except ValueError:
print("Invalid input. Please enter a valid number.")
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print(f"Result: {result}")
```
### 4. Using `finally` without `except`:
```python
try:
file = open("nonexistent_file.txt", "r")
except FileNotFoundError:
print("File not found.")
finally:
print("This block always executed, even if there is no exception.")
```
### 5. Handling Multiple Exceptions in One `except` Block:
```python
try:
x = 10 / 0 # Division by zero
except (ZeroDivisionError, NameError, TypeError) as e:
print(f"Error: {e}")
```
### 6. Raising Exceptions:
```python
try:
age = int(input("Enter your age: "))
if age < 0:
raise ValueError("Age cannot be negative.")
except ValueError as ve:
print(f"Error: {ve}")
```These examples cover a range of scenarios for handling exceptions in Python. Understanding and using exception
handling effectively can make your programs more robust and resilient to unexpected issues.
File handling in Python:
### 1. Writing to a File:
```python
# Writing to a file
with open("example.txt", "w") as file:
file.write("Hello, this is a sample file.\n")
file.write("Python is awesome!\n")
```
### 2. Reading from a File:
```python
# Reading from a file
with open("example.txt", "r") as file:
content = file.read()
print("File Content:\n", content)
```
### 3. Appending to a File:
```python
# Appending to a file
with open("example.txt", "a") as file:
file.write("Appending new content to the file.\n")
```
### 4. Reading Line by Line:
```python
# Reading line by line
with open("example.txt", "r") as file:
lines = file.readlines()
print("Lines in the File:")
for line in lines:
print(line.strip())
```
### 5. Handling Exceptions during File Operations:
```python
try:
with open("nonexistent_file.txt", "r") as file:
content = file.read()
print(content)
except FileNotFoundError:
print("File not found.")
except Exception as e:
print(f"An error occurred: {e}")
```
### 6. Copying a File:
```python
source_file = "example.txt"
destination_file = "copy_of_example.txt"
try:
with open(source_file, "r") as source, open(destination_file, "w") as dest:
content = source.read()
dest.write(content)
print(f"File '{source_file}' copied to '{destination_file}'.")
except FileNotFoundError:
print("Source file not found.")
except Exception as e:
print(f"An error occurred: {e}")
```
### 7. Using `with` Statement for Multiple Files:
```python
with open("file1.txt", "r") as file1, open("file2.txt", "r") as file2:
content1 = file1.read()
content2 = file2.read()
print("Content of file1:\n", content1)
print("Content of file2:\n", content2)
```
These examples cover basic file handling operations such as reading, writing, appending, and handling exceptions
during file operations. Depending on your requirements, you can adapt and extend these examples for more complex
scenarios.