1. Python Basics
Python is a high-level, interpreted programming language known for its readability, simplicity, and versatility. Created by Guido van Rossum and first released in 1991, Python supports multiple programming paradigms, including object-oriented, procedural, and functional programming.
Key Features of Python:
Easy to Learn and Use: Python has a simple syntax that closely resembles English, making it straightforward to learn and use for both beginners and experienced programmers.
Interpreted Language: Python code is executed line by line, which makes debugging easier and allows for rapid development.
Dynamically Typed: Python does not require explicit declaration of variable types. Types are determined at runtime, which adds flexibility but can increase the potential for runtime errors.
Extensive Standard Library: Python’s standard library includes modules and packages for various tasks, such as file I/O, regular expressions, and more, reducing the need for additional libraries.
Cross-Platform Compatibility: Python is cross-platform and can run on various operating systems, including Windows, macOS, and Linux, without requiring changes to the code.
Object-Oriented and Functional Programming: Python supports both object-oriented and functional programming paradigms, allowing for different approaches to solving problems.
Large Community and Ecosystem: Python has a vast community and ecosystem, with numerous libraries and frameworks (like Django for web development, Pandas for data analysis, and TensorFlow for machine learning) that extend its functionality.
Automatic Memory Management: Python handles memory allocation and deallocation automatically through its garbage collection system, making it easier to manage resources without manual intervention.
Integration Capabilities: Python can easily integrate with other languages like C, C++, and Java, and is often used as a scripting language for automating workflows.
Python is different from many other programming languages due to its simplicity and versatility. Below are some of its key distinguishing features:
- Simplicity: Python’s syntax is clean and easy to learn, making it beginner-friendly.
- Readability: Python code is designed to be easily readable and maintainable.
- Interpreted Language: Python is an interpreted language, which means it executes code line by line, making debugging easier.
- Extensive Libraries: Python comes with a vast standard library and supports numerous third-party modules.
- Dynamic Typing: Python does not require explicit type declarations; variables are dynamically typed.
- Portability: Python programs can run on different platforms without requiring modifications.
- Versatility: Python is used in web development, data analysis, artificial intelligence, scientific computing, and more.
Example Code:
# Example of Python’s simplicity
for i in range(1, 6):
print(f“Number: {i}”)
Python being an interpreted language means that its code is executed line by line by the Python interpreter, rather than being compiled into machine code beforehand. This has several implications:
- Ease of Debugging: Errors are reported immediately as the program runs, making it easier to identify and fix issues.
- Platform Independence: Python programs can run on any system with a compatible interpreter, without the need for recompilation.
- Dynamic Typing: Variables in Python are dynamically typed, which is handled by the interpreter during runtime.
- Interactive Testing: Python’s interactive shell allows developers to execute code snippets and test them on the fly.
Example Code:
# Python code can be executed line by line
x = 10 # Step 1
y = 20 # Step 2
print(“Sum: {x + y}”) # Step 3
Python 2 and Python 3 are major versions of Python, and they have significant differences. Python 3 was introduced to address the limitations of Python 2 and to modernize the language. Here are the key differences:
- Print Statement:
- Python 2:
print "Hello"
- Python 3:
print("Hello")
(requires parentheses)
- Python 2:
- Unicode Support:
- Python 2: Strings are ASCII by default.
- Python 3: Strings are Unicode by default, making it easier to work with international text.
- Division:
- Python 2:
5 / 2
returns2
(integer division). - Python 3:
5 / 2
returns2.5
(true division).
- Python 2:
- Iterators: Functions like
range()
andzip()
return iterators in Python 3 instead of lists in Python 2. - End of Life: Python 2 is no longer maintained or updated as of January 1, 2020.
Example Code:
# Python 3 example: True division and Unicode strings
print(“Hello, World!”)
result = 5 / 2
print(f“Result: {result}”)
In Python, variables are defined by assigning a value to a variable name. Unlike some programming languages, Python does not require an explicit declaration of variable types. The type of the variable is inferred from the value assigned to it.
Key points about defining variables in Python:
- Dynamic Typing: Variables can hold different data types at different times.
- No Declaration: No need to declare variables or their types before assigning a value.
- Case Sensitivity: Variable names are case-sensitive (
var
andVar
are different). - Naming Rules: Variable names must start with a letter or an underscore and can be followed by letters, digits, or underscores.
Example Code:
# Defining variables in Python
x = 10 # Integer
name = “Alice” # String
price = 19.99 # Float
is_active = True # Boolean
Python is a versatile and widely-used programming language, but like any technology, it has its strengths and weaknesses. Below are its key advantages and disadvantages:
Advantages:
- Easy to Learn and Use: Python’s simple syntax makes it beginner-friendly and promotes productivity.
- Extensive Libraries: A rich standard library and numerous third-party packages simplify complex tasks.
- Platform Independence: Python programs can run on multiple operating systems without modification.
- Versatility: Suitable for web development, data analysis, artificial intelligence, scientific computing, and more.
- Community Support: A large and active community provides extensive documentation and resources.
Disadvantages:
- Performance: Python is slower than compiled languages like C or C++ due to its interpreted nature.
- Memory Usage: Python’s high memory consumption can be a limitation for resource-constrained environments.
- Mobile Development: Python is not ideal for mobile and game development compared to languages like Java or Swift.
- Global Interpreter Lock (GIL): The GIL limits multi-threading performance in CPU-bound tasks.
Example Code:
# Example showcasing Python’s simplicity and limitations
import time
# Python code runs slower in time-intensive tasks
def slow_function():
time.sleep(2) # Introduces delay
print(“Task completed”)
slow_function()
Literals in Python are the constant values assigned to variables or used directly in code. These values represent fixed data and are categorized based on their data types. Here are the main types of literals in Python:
Types of Literals:
- String Literals: Represent text enclosed in single (
' '
) or double quotes (" "
).- Example:
"Hello, World!"
- Example:
- Numeric Literals: Represent numbers and include:
- Integers: Whole numbers (
10
,-5
). - Floats: Decimal numbers (
3.14
,-0.99
). - Complex Numbers: Numbers with a real and imaginary part (
3 + 4j
).
- Integers: Whole numbers (
- Boolean Literals: Represent truth values:
True
orFalse
. - Special Literal:
None
, representing the absence of a value or a null value. - Collection Literals: Represent collections of data such as lists, tuples, sets, and dictionaries.
- Example:
[1, 2, 3]
,{'a': 1, 'b': 2}
- Example:
Example Code:
# Examples of Python literals
string_literal = “Python”
int_literal = 100
float_literal = 3.14
bool_literal = True
none_literal = None
list_literal = [1, 2, 3]
Python’s memory management mechanism involves efficient allocation and deallocation of memory for objects and data structures. It is handled automatically by Python’s internal memory manager, making it easier for developers to focus on writing code without worrying about manual memory management.
Key Aspects of Python’s Memory Management:
- Dynamic Memory Allocation: Memory is allocated dynamically when objects are created, and the size can grow or shrink as needed.
- Reference Counting: Python tracks the number of references to an object. When an object’s reference count drops to zero, it is marked for garbage collection.
- Garbage Collection: Python’s garbage collector reclaims memory from objects no longer in use. It uses techniques like reference counting and cycle detection to identify unused objects.
- Private Heap: All Python objects and data structures are stored in a private heap, managed by Python’s memory manager.
- Memory Pools: Python optimizes memory allocation for small objects by using memory pools to reduce fragmentation and improve performance.
Example Code:
# Example demonstrating reference counting and garbage collection
import gc # Import garbage collection module
class Example:
def __init__(self):
print(“Object created”)
def __del__(self):
print(“Object destroyed”)
obj = Example() # Create an object
del obj # Delete the object to trigger garbage collection
gc.collect() # Force garbage collection
Python provides several built-in data types to handle different kinds of data. These data types can be broadly categorized into the following groups:
1. Numeric Types:
- int: Represents integers, e.g.,
10
,-5
. - float: Represents floating-point numbers, e.g.,
3.14
,-0.99
. - complex: Represents complex numbers with real and imaginary parts, e.g.,
3 + 4j
.
2. Sequence Types:
- str: Represents strings, e.g.,
"Hello"
,'Python'
. - list: Represents an ordered collection of items, e.g.,
[1, 2, 3]
. - tuple: Represents an immutable ordered collection, e.g.,
(1, 2, 3)
.
3. Set Types:
- set: Represents an unordered collection of unique items, e.g.,
{1, 2, 3}
. - frozenset: An immutable version of a set.
4. Mapping Types:
- dict: Represents key-value pairs, e.g.,
{"a": 1, "b": 2}
.
5. Boolean Type:
- bool: Represents truth values,
True
orFalse
.
6. None Type:
- NoneType: Represents the absence of a value, e.g.,
None
.
Example Code:
# Examples of Python’s built-in data types
x = 10 # int
y = 3.14 # float
z = 3 + 4j # complex
name = “Alice” # str
my_list = [1, 2, 3] # list
my_tuple = (1, 2, 3) # tuple
my_set = {1, 2, 3} # set
my_dict = {“a”: 1, “b”: 2} # dict
is_active = True # bool
no_value = None # NoneType
Comments in Python are used to explain the code and make it more readable. They are ignored by the Python interpreter and do not affect the execution of the program. Python supports two types of comments:
1. Single-line Comments:
Single-line comments begin with the hash symbol (#
). Everything after the #
on that line is treated as a comment.
2. Multi-line Comments:
Python does not have a specific syntax for multi-line comments. However, multi-line comments can be achieved using triple quotes ('''
or """
) as a string, which is not assigned to any variable and is thus ignored by the interpreter.
Example Code:
# This is a single-line comment
x = 10 # Variable to store a number
”’
This is a
multi-line comment
using triple quotes
”’
print(“Hello, Python!”)
2. Data Structures
Python provides several built-in data types to store collections of data. Below is a comparison of lists, tuples, sets, and dictionaries:
1. List:
- Definition: An ordered, mutable collection of items.
- Syntax:
[item1, item2, item3]
- Example:
my_list = [1, 2, 3, 4]
2. Tuple:
- Definition: An ordered, immutable collection of items.
- Syntax:
(item1, item2, item3)
- Example:
my_tuple = (1, 2, 3, 4)
3. Set:
- Definition: An unordered, mutable collection of unique items.
- Syntax:
{item1, item2, item3}
- Example:
my_set = {1, 2, 3, 4}
4. Dictionary:
- Definition: An unordered collection of key-value pairs.
- Syntax:
{key1: value1, key2: value2}
- Example:
my_dict = {"a": 1, "b": 2}
Comparison Table:
Feature | List | Tuple | Set | Dictionary |
---|---|---|---|---|
Ordered | Yes | Yes | No | No |
Mutable | Yes | No | Yes | Yes |
Duplicates Allowed | Yes | Yes | No | Keys: No, Values: Yes |
Key-Value Pair | No | No | No | Yes |
Example Code:
# List
my_list = [1, 2, 3]
# Tuple
my_tuple = (1, 2, 3)
# Set
my_set = {1, 2, 3}
# Dictionary
my_dict = {“a”: 1, “b”: 2}
A list in Python is a collection of items that can store multiple values in a single variable. Lists are:
- Ordered: The items have a defined order.
- Mutable: You can change, add, or remove items after the list is created.
- Allows Duplicates: A list can have multiple items with the same value.
Creating a List:
To create a list, enclose the items in square brackets []
and separate them with commas.
Syntax:
# Creating a list
my_list = [item1, item2, item3]
Example Code:
# Creating a list of numbers
numbers = [1, 2, 3, 4]
# Creating a list of strings
fruits = [“apple”, “banana”, “cherry”]
# Creating a mixed-type list
mixed = [1, “hello”, 3.14]
# Creating an empty list
empty_list = []
Accessing and Modifying a List:
- Access items: Use indexing, e.g.,
numbers[0]
returns1
. - Modify items: Assign a new value to an index, e.g.,
numbers[1] = 5
.
Tab Content
Tab Content
Tab Content
Tab Content
Tab Content
Tab Content
Tab Content