Data Type in Python
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:**
```python
# Numeric types
integer_variable = 10
float_variable = 3.14
```
2. **Sequence Types:**
```python
# Sequence types
list_variable = [1, 2, 3]
tuple_variable = (4, 5, 6)
```
3. **Set Types:**
```python
# Set type
set_variable = {1, 2, 3}
```
4. **Mapping Type:**
# Dictionary type
```
5. **Boolean Type:**
```python
# Boolean type
boolean_variable = True
```
6. **None Type:**
```python
# None type
none_variable = None
```
7. **Other Types:**
```python
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:
```python
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n-1)
result = factorial(5)
```
```python
def fibonacci(n):
if n <= 1:
return n
else:
for i in range(6):
print(f"Fibonacci({i}) = {fibonacci(i)}")
```
```python
if n > 0:
```
```python
if arr[mid] == target:
return mid
else:
else:
return -1
if result != -1:
else:
```
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:
You can create a list by enclosing elements in square brackets `[]` and separating them with commas.
```python
my_list = [1, 2, 3, 4, 5]
empty_list = []
```
You can access individual elements in a list using index notation. Python uses zero-based indexing.
```python
print(my_list[0]) # Output: 1
```
```python
my_list[2] = 10
```
```python
# Concatenation
# 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
```
```python
```
### Slicing:
You can extract a sublist (slice) from a list using slicing notation.
```python
```
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:
The `for` loop is used to iterate over a sequence (such as a list, tuple, string, or range).
```python
print(fruit)
```
```python
print(i)
```
The `while` loop continues to execute a block of code as long as a specified condition is true.
```python
i=1
while i <= 5:
print(i)
i += 1
```
You can use the `enumerate` function to iterate over both elements and their indices in a sequence.
```python
```
### 4. **Iterating Over Dictionaries:**
You can iterate over the keys, values, or key-value pairs of a dictionary.
```python
print(f"{key}: {value}")
```
List comprehensions provide a concise way to create lists and perform iteration in a single line.
```python
```
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
if i == 5:
break
print(i)
```
```python
# Using continue
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:
You can create a string by enclosing characters within single (`'`) or double (`"`) quotes.
```python
```
1. **Concatenation:**
```python
print(concatenated_str)
```
2. **Repetition:**
```python
repeated_str = str1 * 3
print(repeated_str)
```
3. **Indexing:**
```python
first_char = str1[0]
last_char = str1[-1]
```
4. **Slicing:**
```python
```
5. **String Length:**
```python
length = len(str1)
```
6. **String Methods:**
```python
upper_case = str1.upper()
lower_case = str1.lower()
is_alpha = str1.isalpha()
```
```python
```
```python
name = "John"
age = 25
```
In Python 3.6 and above, you can use f-strings for a more concise way of formatting:
```python
```
### String Methods:
Python provides a rich set of methods for string manipulation. Some commonly used methods include:
```python
uppercase_text = text.upper()
```
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:
self.name = name
self.age = age
def display_info(self):
class Student(Person):
super().__init__(name, age)
self.student_id = student_id
def display_info(self):
class Teacher(Person):
super().__init__(name, age)
self.employee_id = employee_id
def display_info(self):
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:
# Private attributes
self.__name = name
self.__age = age
self.__student_id = student_id
def get_name(self):
return self.__name
def get_age(self):
return self.__age
def get_student_id(self):
return self.__student_id
self.__age = new_age
else:
def display_info(self):
print("Name:", student1.get_name())
print("Age:", student1.get_age())
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:
```python
try:
x = 10 / 0 # Division by zero
except ZeroDivisionError as e:
print(f"Error: {e}")
else:
finally:
```
```python
class CustomError(Exception):
self.message = message
try:
```
```python
try:
except ValueError:
else:
print(f"Result: {result}")
```
```python
try:
except FileNotFoundError:
finally:
```
```python
try:
x = 10 / 0 # Division by zero
print(f"Error: {e}")
```
```python
try:
if age < 0:
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
file.write("Python is awesome!\n")
```
```python
content = file.read()
```
```python
# Appending to a file
```
```python
lines = file.readlines()
print(line.strip())
```
```python
try:
print(content)
except FileNotFoundError:
except Exception as e:
```
```python
source_file = "example.txt"
destination_file = "copy_of_example.txt"
try:
content = source.read()
dest.write(content)
except FileNotFoundError:
except Exception as e:
```
```python
content1 = file1.read()
content2 = file2.read()
```
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.