Output:
Worker thread
Python is a high-level, interpreted programming language that emphasizes readability and simplicity, making it a popular choice for both beginners and professionals.
Python is widely used in various domains including web development, data science, machine learning, and automation.
Python supports multiple programming paradigms such as procedural, object-oriented, and functional programming. Its simple syntax makes it ideal for new programmers.
Python was created by Guido van Rossum in 1989. It was released to the public in 1991 and has since grown to be one of the most popular programming languages.
Python is interpreted and dynamically typed, while C++ is compiled and statically typed. Python’s syntax is simpler, making it easier for beginners to learn, whereas C++ offers more control over hardware and performance.
To print "Hello, World!" in Python:
# Hello World Program
print("Hello, World!")
The Python interpreter executes Python code line-by-line, making debugging easier and faster. Python is an interpreted language, meaning the code is executed directly from source code without the need for compilation.
To set up Python, download and install it from the official website. You can use any IDE or text editor (VS Code, PyCharm) to write Python code.
A virtual environment helps to create isolated spaces for different projects, avoiding conflicts between dependencies.
# Create a virtual environment
python -m venv myenv
Python uses indentation to define the scope of loops, functions, and classes. Here is an example:
# Basic Syntax Example
if True:
print("This is correct indentation.")
In Python, variables are used to store data, and you do not need to declare their type explicitly. Example:
# Variables Example
x = 10 # integer
y = "Python" # string
Python supports various data types like integers, floats, strings, lists, and more. Example:
# Data Types Example
x = 5 # Integer
y = 3.14 # Float
z = "Hello" # String
Type casting refers to converting one data type to another. Example:
# Type Casting Example
x = 10 # integer
y = float(x) # convert to float
print(y)
10.0
Python supports Unicode, allowing characters from various languages to be used in strings. Example:
# Unicode Example
text = "Hello, World! 😀"
print(text)
Hello, World! 😀
Literals are fixed values that appear directly in the code. Example:
# Literals Example
a = 100 # Integer literal
b = 3.14 # Float literal
c = "Hello" # String literal
Operators are used to perform operations on variables and values. Python supports various operators such as arithmetic, comparison, and logical operators.
Arithmetic operators allow us to perform basic mathematical operations. Example:
# Arithmetic Operators Example
a = 10
b = 5
print(a + b) # Addition
print(a - b) # Subtraction
print(a * b) # Multiplication
print(a / b) # Division
15
5
50
2.0
Comparison operators are used to compare two values. Example:
# Comparison Operators Example
a = 10
b = 5
print(a > b) # Greater than
print(a < b) # Less than
print(a == b) # Equal to
True
False
False
Assignment operators are used to assign values to variables. Examples of assignment operators include '=', '+=', '-=', '*=', and others.
# Assignment Operators Example
a = 10
a += 5 # a = a + 5
print(a)
b = 20
b -= 3 # b = b - 3
print(b)
c = 5
c *= 4 # c = c * 4
print(c)
15
17
20
Logical operators are used to combine conditional statements. The common logical operators are `and`, `or`, and `not`.
# Logical Operators Example
a = True
b = False
print(a and b) # AND operation
print(a or b) # OR operation
print(not a) # NOT operation
False
True
False
Bitwise operators work on the binary representations of numbers. These include `&`, `|`, `^`, `~`, `<<`, and `>>`.
# Bitwise Operators Example
a = 5 # 0101 in binary
b = 3 # 0011 in binary
print(a & b) # AND
print(a | b) # OR
print(a ^ b) # XOR
1
7
6
Membership operators `in` and `not in` are used to test if a value or variable is found in a sequence (such as a list, tuple, or string).
# Membership Operators Example
a = [1, 2, 3, 4]
print(3 in a) # Check if 3 is in the list
print(5 not in a) # Check if 5 is not in the list
True
True
Identity operators are used to compare the memory locations of two objects. The operators are `is` and `is not`.
# Identity Operators Example
a = [1, 2, 3]
b = a
print(a is b) # Check if both variables point to the same object
print(a is not b) # Check if both variables do not point to the same object
True
False
Operator precedence refers to the order in which operators are evaluated. In Python, the following precedence applies:
# Operator Precedence Example
result = 3 + 2 * 5 # Multiplication is done first, then addition
print(result)
result2 = (3 + 2) * 5 # Parentheses change the precedence
print(result2)
13
25
Comments in Python are written using the `#` symbol. They are not executed and are used for documentation or explanation of the code.
# This is a single-line comment
x = 5 # Variable assignment
'''
This is a
multi-line comment
'''
print(x)
To accept input from the user, use the `input()` function. The input is always returned as a string.
# User Input Example
name = input("Enter your name: ")
age = input("Enter your age: ")
print(f"Hello {name}, you are {age} years old.")
Enter your name: John
Enter your age: 25
Hello John, you are 25 years old.
Python supports three types of numbers: integers, floating point numbers, and complex numbers.
# Numbers Example
x = 10 # Integer
y = 3.14 # Float
z = 2 + 3j # Complex number
print(x, y, z)
10 3.14 (2+3j)
Booleans represent one of two values: True or False. They are used to perform logical operations and control the flow of the program using conditional statements.
# Booleans Example
a = True
b = False
# Logical operations
print(a and b) # AND operation
print(a or b) # OR operation
print(not a) # NOT operation
False
True
False
Control statements allow you to control the flow of execution in your program based on certain conditions. They include conditional statements and loops.
# Control Statements Example
x = 5
if x > 3:
print("x is greater than 3")
else:
print("x is not greater than 3")
x is greater than 3
Control flow in Python refers to the order in which individual statements, instructions, or function calls are executed or evaluated.
# Control Flow Example
x = 10
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is 5")
else:
print("x is less than 5")
x is greater than 5
Decision-making statements help you to execute certain blocks of code based on conditions, like `if`, `else`, and `elif`.
# Decision Making Example
age = 20
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
You are eligible to vote.
The `if` statement is used to check a condition, and if the condition is true, the block of code under it will execute.
# If Statement Example
x = 10
if x > 5:
print("x is greater than 5")
x is greater than 5
The `if-else` statement helps you perform one action if a condition is true and another if it is false.
# If Else Example
x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
x is not greater than 5
Nested `if` statements are `if` statements inside another `if` statement, used to check multiple conditions.
# Nested If Example
x = 10
if x > 5:
if x < 15:
print("x is between 5 and 15")
else:
print("x is greater than or equal to 15")
x is between 5 and 15
The `match-case` statement in Python allows pattern matching. It's similar to `switch-case` in other programming languages, introduced in Python 3.10.
# Match-Case Example
day = "Monday"
match day:
case "Monday":
print("Start of the work week!")
case "Friday":
print("Almost weekend!")
case _:
print("Midweek")
Start of the work week!
Loops allow you to execute a block of code repeatedly. Python supports `for` and `while` loops.
# Loops Example
for i in range(3):
print(i)
0
1
2
The `for` loop is used to iterate over a sequence (such as a list, tuple, or range) and execute a block of code for each item in the sequence.
# For Loops Example
for i in range(4, 7):
print(i)
4
5
6
The `else` block can also be used with a `for` loop. It executes when the loop completes normally (i.e., no `break` statement).
# For-Else Loops Example
for i in range(3):
print(i)
else:
print("Loop finished without interruption.")
0
1
2
Loop finished without interruption.
The `while` loop executes as long as the given condition evaluates to true.
# While Loops Example
i = 0
while i < 3:
print(i)
i += 1
0
1
2
The `break` statement is used to exit the current loop prematurely when a specific condition is met.
# Break Statement Example
for i in range(5):
if i == 3:
break
print(i)
0
1
2
The `continue` statement skips the current iteration of a loop and moves to the next iteration.
# Continue Statement Example
for i in range(5):
if i == 3:
continue
print(i)
0
1
2
4
The `pass` statement is a placeholder that is used when a statement is syntactically required but no action is needed.
# Pass Statement Example
for i in range(5):
if i == 3:
pass
print(i)
0
1
2
3
4
Nested loops are loops within loops. The inner loop is executed completely every time the outer loop runs once.
# Nested Loops Example
for i in range(2):
for j in range(3):
print(f"i={i}, j={j}")
i=0, j=0
i=0, j=1
i=0, j=2
i=1, j=0
i=1, j=1
i=1, j=2
Functions in Python are used to group code into reusable blocks. A function is defined using the `def` keyword.
# Function Example
def greet():
print("Hello, World!")
greet()
Hello, World!
Default arguments allow you to specify default values for parameters in a function. These values are used if no argument is provided when calling the function.
# Default Arguments Example
def greet(name="Guest"):
print(f"Hello, {name}!")
greet("Alice") # Custom argument
greet() # Default argument
Hello, Alice!
Hello, Guest!
Keyword arguments are passed by explicitly specifying the parameter name and its corresponding value.
# Keyword Arguments Example
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")
greet(age=25, name="Bob") # Using keyword arguments
Hello Bob, you are 25 years old.
Keyword-only arguments are arguments that must be specified by keyword (not by position). These are defined after a `*` symbol in the function signature.
# Keyword-Only Arguments Example
def greet(name, *, age):
print(f"Hello {name}, you are {age} years old.")
greet("Alice", age=30) # Correct usage
Hello Alice, you are 30 years old.
Positional arguments are arguments that are assigned to parameters based on their position in the function call.
# Positional Arguments Example
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")
greet("Charlie", 28) # Correct usage
Hello Charlie, you are 28 years old.
Positional-only arguments are arguments that must be passed in a specific order, specified by a `/` in the function signature.
# Positional-Only Arguments Example
def greet(name, /, age):
print(f"Hello {name}, you are {age} years old.")
greet("David", 35) # Correct usage
Hello David, you are 35 years old.
Arbitrary arguments allow you to pass a variable number of arguments to a function. These are defined using `*args` for non-keyword arguments and `**kwargs` for keyword arguments.
# Arbitrary Arguments Example
def greet(*names):
for name in names:
print(f"Hello {name}!")
greet("Alice", "Bob", "Charlie")
Hello Alice!
Hello Bob!
Hello Charlie!
Scope refers to the region where a variable can be accessed. Variables can have global scope or local scope within a function.
# Variables Scope Example
x = 10 # Global variable
def my_func():
y = 20 # Local variable
print(f"x = {x}, y = {y}")
my_func()
print(x) # Global variable can be accessed outside the function
x = 10, y = 20
10
Function annotations provide a way to attach metadata to function parameters and return values using a colon (`:`) and arrow (`->`).
# Function Annotations Example
def greet(name: str, age: int) -> str:
return f"Hello {name}, you are {age} years old."
print(greet("Eve", 22))
Hello Eve, you are 22 years old.
Modules in Python are files containing Python code. A module can define functions, classes, and variables, and can also include runnable code.
# Importing a Module Example
import math
print(math.sqrt(16)) # Using sqrt function from math module
4.0
Python provides a set of built-in functions that are always available. These functions perform common tasks such as input/output, type conversion, and more.
# Built-in Functions Example
print(len("Hello, World!")) # len() function returns the length of the string
13
In Python, strings are sequences of characters enclosed in single quotes (`'`) or double quotes (`"`). Strings are immutable, meaning their values cannot be changed after creation.
# String Example
message = "Hello, World!"
print(message)
Hello, World!
String slicing in Python allows you to extract a portion of a string using the slice operator (`:`). You can specify a start index, an end index, and an optional step value.
# Slicing Strings Example
text = "Hello, World!"
print(text[0:5]) # Extracts from index 0 to 5 (not including 5)
print(text[:5]) # Extracts from the beginning to index 5
print(text[7:]) # Extracts from index 7 to the end
Hello
Hello
World!
Strings in Python are immutable, meaning you cannot directly modify a string. However, you can create a new string by concatenating or manipulating the original string.
# Modify Strings Example
text = "Hello"
new_text = text + " World!"
print(new_text)
Hello World!
String concatenation is the process of joining two or more strings together using the `+` operator in Python.
# String Concatenation Example
greeting = "Hello"
name = "Alice"
message = greeting + " " + name
print(message)
Hello Alice
String formatting allows you to insert variables or expressions into strings. Python provides multiple ways for string formatting, such as f-strings and the `format()` method.
# String Formatting Example using f-string
name = "Alice"
age = 25
message = f"Hello {name}, you are {age} years old."
print(message)
# String Formatting Example using format()
message = "Hello {}, you are {} years old.".format(name, age)
print(message)
Hello Alice, you are 25 years old.
Hello Alice, you are 25 years old.
Escape characters in Python allow you to represent special characters that are difficult or impossible to express directly, such as newlines or quotes within a string.
# Escape Characters Example
message = "Hello\nWorld!"
print(message)
message = "She said, \"Hello!\""
print(message)
Hello
World!
She said, "Hello!"
Python provides several built-in methods to manipulate strings. Some commonly used methods are `upper()`, `lower()`, and `replace()`.
# String Methods Example
text = "Hello, World!"
print(text.upper()) # Converts to uppercase
print(text.lower()) # Converts to lowercase
print(text.replace("World", "Python")) # Replaces a part of the string
HELLO, WORLD!
hello, world!
Hello, Python!
Below are a couple of exercises that help you practice string manipulation in Python.
# Exercise 1: Count occurrences of a character
text = "hello, hello world"
count = text.count("l")
print(count)
# Exercise 2: Reverse a string
reversed_text = text[::-1]
print(reversed_text)
4
dlrow olleh ,olleh
A list in Python is a collection of ordered, changeable, and mutable items. Lists are defined using square brackets `[]` and allow duplicate values.
# Example of List
fruits = ["apple", "banana", "cherry"]
print(fruits)
['apple', 'banana', 'cherry']
Lists in Python can be accessed using index numbers. The first element has index 0, the second element index 1, and so on. Negative indexing starts from the last element.
# Accessing List Items
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Accessing first item
print(fruits[-1]) # Accessing last item
apple
cherry
You can change the value of an item in a list by assigning a new value to an existing index.
# Changing List Items
fruits = ["apple", "banana", "cherry"]
fruits[1] = "orange" # Changing "banana" to "orange"
print(fruits)
['apple', 'orange', 'cherry']
Lists in Python allow you to add new elements using methods such as `append()`, `insert()`, and `extend()`.
# Adding Items to List
fruits = ["apple", "banana", "cherry"]
fruits.append("orange") # Adds "orange" to the end of the list
fruits.insert(1, "grapes") # Inserts "grapes" at index 1
fruits.extend(["pear", "melon"]) # Adds multiple items at the end
print(fruits)
['apple', 'grapes', 'banana', 'cherry', 'orange', 'pear', 'melon']
You can remove items from a list using `remove()`, `pop()`, or `clear()` methods.
# Removing Items from List
fruits = ["apple", "banana", "cherry", "orange"]
fruits.remove("banana") # Removes "banana"
fruits.pop(1) # Removes item at index 1 (cherry)
fruits.clear() # Removes all items
print(fruits)
[]
You can loop through the elements of a list using a `for` loop.
# Looping through List
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
apple
banana
cherry
List comprehensions allow you to create new lists from existing lists in a concise way.
# List Comprehension Example
fruits = ["apple", "banana", "cherry"]
new_fruits = [fruit.upper() for fruit in fruits]
print(new_fruits)
['APPLE', 'BANANA', 'CHERRY']
You can sort lists using the `sort()` method which arranges elements in ascending order. You can also sort in descending order using `reverse=True`.
# Sorting a List
fruits = ["apple", "banana", "cherry"]
fruits.sort() # Sorts in ascending order
print(fruits)
fruits.sort(reverse=True) # Sorts in descending order
print(fruits)
['apple', 'banana', 'cherry']
['cherry', 'banana', 'apple']
Use the `copy()` method to create a shallow copy of a list.
# Copying List
fruits = ["apple", "banana", "cherry"]
new_fruits = fruits.copy()
print(new_fruits)
['apple', 'banana', 'cherry']
You can join two or more lists using the `+` operator or `extend()` method.
# Joining Lists
fruits = ["apple", "banana"]
vegetables = ["carrot", "tomato"]
combined = fruits + vegetables
print(combined)
['apple', 'banana', 'carrot', 'tomato']
List methods include `append()`, `remove()`, `insert()`, `pop()`, `sort()`, etc. Below is an example of using multiple methods together.
# List Methods Example
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
fruits.remove("banana")
fruits.insert(1, "grapes")
print(fruits)
['apple', 'grapes', 'cherry', 'orange']
Below are a couple of exercises that help you practice list manipulation in Python.
# Exercise 1: Create a list of numbers from 1 to 10
numbers = list(range(1, 11))
print(numbers)
# Exercise 2: Remove all odd numbers from the list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[2, 4, 6, 8, 10]
A tuple in Python is an ordered collection of elements, enclosed in parentheses `()` and can contain different types of elements. Tuples are immutable, meaning you cannot modify their values once they are created.
# Example of Tuple
fruits = ("apple", "banana", "cherry")
print(fruits)
('apple', 'banana', 'cherry')
You can access items in a tuple by their index. Indexing starts at 0, and negative indexing starts from the last element.
# Accessing Tuple Items
fruits = ("apple", "banana", "cherry")
print(fruits[0]) # Accessing first item
print(fruits[-1]) # Accessing last item
apple
cherry
Tuples are immutable, meaning you cannot change their elements directly. However, you can convert a tuple to a list, make the changes, and convert it back to a tuple.
# Updating a Tuple
fruits = ("apple", "banana", "cherry")
temp_list = list(fruits) # Convert tuple to list
temp_list[1] = "orange" # Update the list
fruits = tuple(temp_list) # Convert list back to tuple
print(fruits)
('apple', 'orange', 'cherry')
Tuple unpacking allows you to assign elements of a tuple to multiple variables in a single statement.
# Unpacking a Tuple
fruits = ("apple", "banana", "cherry")
fruit1, fruit2, fruit3 = fruits
print(fruit1)
print(fruit2)
print(fruit3)
apple
banana
cherry
You can loop through a tuple using a `for` loop.
# Looping through Tuple
fruits = ("apple", "banana", "cherry")
for fruit in fruits:
print(fruit)
apple
banana
cherry
You can join two or more tuples using the `+` operator.
# Joining Tuples
tuple1 = ("apple", "banana")
tuple2 = ("cherry", "orange")
joined_tuple = tuple1 + tuple2
print(joined_tuple)
('apple', 'banana', 'cherry', 'orange')
Tuples support a few methods like `count()` and `index()` for counting elements and finding their position in the tuple.
# Tuple Methods Example
fruits = ("apple", "banana", "cherry", "banana")
count_banana = fruits.count("banana")
index_apple = fruits.index("apple")
print("Count of 'banana':", count_banana)
print("Index of 'apple':", index_apple)
Count of 'banana': 2
Index of 'apple': 0
Below are a couple of exercises that help you practice tuple manipulation in Python.
# Exercise 1: Create a tuple with numbers from 1 to 5
numbers = (1, 2, 3, 4, 5)
print(numbers)
# Exercise 2: Find the index of an item in the tuple
fruits = ("apple", "banana", "cherry")
index_of_banana = fruits.index("banana")
print("Index of 'banana':", index_of_banana)
(1, 2, 3, 4, 5)
Index of 'banana': 1
A set in Python is an unordered collection of unique elements. Sets are written with curly braces `{}` and they do not allow duplicate values.
# Example of Set
fruits = {"apple", "banana", "cherry"}
print(fruits)
{'apple', 'banana', 'cherry'}
Since sets are unordered collections, they do not support indexing. However, you can loop through the set to access its items.
# Accessing Set Items
fruits = {"apple", "banana", "cherry"}
for fruit in fruits:
print(fruit)
apple
banana
cherry
To add items to a set, you can use the `add()` method. It adds one item to the set at a time.
# Adding Set Items
fruits = {"apple", "banana", "cherry"}
fruits.add("orange")
print(fruits)
{'apple', 'banana', 'cherry', 'orange'}
You can remove items from a set using the `remove()` method. If the item does not exist, it raises a `KeyError`. Alternatively, you can use the `discard()` method, which does not raise an error if the item is not found.
# Removing Set Items
fruits = {"apple", "banana", "cherry"}
fruits.remove("banana")
print(fruits)
{'apple', 'cherry'}
You can loop through the set using a `for` loop.
# Looping through Set
fruits = {"apple", "banana", "cherry"}
for fruit in fruits:
print(fruit)
apple
banana
cherry
You can join two or more sets using the `union()` method or the `|` operator.
# Joining Sets
set1 = {"apple", "banana"}
set2 = {"cherry", "orange"}
joined_set = set1.union(set2)
print(joined_set)
{'banana', 'orange', 'cherry', 'apple'}
To copy a set, you can use the `copy()` method.
# Copying a Set
fruits = {"apple", "banana", "cherry"}
fruits_copy = fruits.copy()
print(fruits_copy)
{'banana', 'cherry', 'apple'}
Python sets support several operators, including union (`|`), intersection (`&`), difference (`-`), and symmetric difference (`^`).
# Set Operators Example
set1 = {"apple", "banana", "cherry"}
set2 = {"banana", "cherry", "date"}
# Union
union_set = set1 | set2
print("Union:", union_set)
# Intersection
intersection_set = set1 & set2
print("Intersection:", intersection_set)
# Difference
difference_set = set1 - set2
print("Difference:", difference_set)
# Symmetric Difference
sym_diff_set = set1 ^ set2
print("Symmetric Difference:", sym_diff_set)
Union: {'apple', 'banana', 'cherry', 'date'}
Intersection: {'banana', 'cherry'}
Difference: {'apple'}
Symmetric Difference: {'apple', 'date'}
Sets support various methods, such as `add()`, `remove()`, `discard()`, `clear()`, `pop()`, `union()`, and `intersection()`.
# Set Methods Example
fruits = {"apple", "banana", "cherry"}
fruits.add("orange") # Add an item
fruits.remove("banana") # Remove an item
fruits.discard("grapes") # Discard an item without error
fruits.clear() # Clear the set
print(fruits)
set()
Below are a couple of exercises that help you practice set manipulation in Python.
# Exercise 1: Create a set of numbers and find the union and intersection
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print("Union:", set1 | set2)
print("Intersection:", set1 & set2)
# Exercise 2: Remove an item from the set
fruits = {"apple", "banana", "cherry"}
fruits.remove("banana")
print(fruits)
Union: {1, 2, 3, 4, 5, 6}
Intersection: {3, 4}
{'apple', 'cherry'}
A dictionary in Python is an unordered collection of items. It consists of key-value pairs, where each key is unique. Dictionaries are written using curly braces `{}`.
# Example of Dictionary
person = {"name": "John", "age": 30, "city": "New York"}
print(person)
{'name': 'John', 'age': 30, 'city': 'New York'}
To access the values in a dictionary, you can use the keys. You can access the value of a specific key by referencing the key in square brackets or using the `get()` method.
# Accessing Dictionary Items
person = {"name": "John", "age": 30, "city": "New York"}
print(person["name"]) # Using square brackets
print(person.get("age")) # Using get method
John
30
You can change the value associated with a key by simply assigning a new value to the key.
# Changing Dictionary Items
person = {"name": "John", "age": 30, "city": "New York"}
person["age"] = 31
print(person)
{'name': 'John', 'age': 31, 'city': 'New York'}
To add a new key-value pair to a dictionary, simply assign a value to a new key.
# Adding Dictionary Items
person = {"name": "John", "age": 30, "city": "New York"}
person["email"] = "john@example.com"
print(person)
{'name': 'John', 'age': 30, 'city': 'New York', 'email': 'john@example.com'}
You can remove items from a dictionary using the `pop()` method, which removes the specified key and returns the value. Alternatively, you can use `del` to remove an item.
# Removing Dictionary Items
person = {"name": "John", "age": 30, "city": "New York"}
person.pop("age") # Using pop
del person["city"] # Using del
print(person)
{'name': 'John'}
Dictionaries in Python provide view objects that allow you to see the keys, values, or key-value pairs. You can use `keys()`, `values()`, or `items()` methods to get these view objects.
# Dictionary View Objects
person = {"name": "John", "age": 30, "city": "New York"}
print(person.keys()) # Keys view object
print(person.values()) # Values view object
print(person.items()) # Items view object
dict_keys(['name', 'age', 'city'])
dict_values(['John', 30, 'New York'])
dict_items([('name', 'John'), ('age', 30), ('city', 'New York')])
You can loop through a dictionary by using a `for` loop. You can loop through keys, values, or both key-value pairs.
# Looping through Dictionary
person = {"name": "John", "age": 30, "city": "New York"}
# Loop through keys
for key in person:
print(key)
# Loop through values
for value in person.values():
print(value)
# Loop through key-value pairs
for key, value in person.items():
print(key, value)
name
age
city
John
30
New York
name John
age 30
city New York
You can create a copy of a dictionary using the `copy()` method. This creates a shallow copy of the dictionary.
# Copying Dictionary
person = {"name": "John", "age": 30, "city": "New York"}
person_copy = person.copy()
print(person_copy)
{'name': 'John', 'age': 30, 'city': 'New York'}
A nested dictionary is a dictionary inside another dictionary. You can access the inner dictionary using the outer dictionary's key.
# Nested Dictionary
person = {
"name": "John",
"details": {"age": 30, "city": "New York"}
}
print(person["details"]["age"]) # Access nested dictionary value
30
Dictionaries have various built-in methods like `clear()`, `get()`, `pop()`, `popitem()`, `update()`, and `setdefault()` that allow you to manipulate dictionary data.
# Dictionary Methods Example
person = {"name": "John", "age": 30, "city": "New York"}
person.clear() # Clear all items from dictionary
print(person)
{}
Below are a couple of exercises that help you practice dictionary manipulation in Python.
# Exercise 1: Create a dictionary and update it
person = {"name": "John", "age": 30, "city": "New York"}
person["age"] = 31
person["email"] = "john@example.com"
print(person)
# Exercise 2: Remove a key from the dictionary
person = {"name": "John", "age": 30, "city": "New York"}
person.pop("age")
print(person)
{'name': 'John', 'age': 31, 'city': 'New York', 'email': 'john@example.com'}
{'name': 'John', 'city': 'New York'}
An array in Python is a data structure used to store a collection of items, which can be of the same type. The `array` module is used to create arrays in Python.
# Example of Array
import array
arr = array.array('i', [1, 2, 3, 4, 5])
print(arr)
array('i', [1, 2, 3, 4, 5])
Array items can be accessed by referring to their index. Indexing starts at 0 in Python arrays.
# Accessing Array Items
import array
arr = array.array('i', [1, 2, 3, 4, 5])
print(arr[0]) # First item
print(arr[3]) # Fourth item
1
4
You can add new items to an array using the `append()` method or by inserting an item at a specific index using the `insert()` method.
# Adding Array Items
import array
arr = array.array('i', [1, 2, 3])
arr.append(4) # Adding item at the end
arr.insert(2, 5) # Inserting item at index 2
print(arr)
array('i', [1, 2, 5, 3, 4])
You can remove array items using the `remove()` method, or you can use `pop()` to remove an item at a specified index.
# Removing Array Items
import array
arr = array.array('i', [1, 2, 3, 4, 5])
arr.remove(3) # Remove first occurrence of 3
arr.pop(2) # Remove item at index 2
print(arr)
array('i', [1, 2, 4, 5])
You can loop through an array using a `for` loop or a `while` loop.
# Looping through Arrays
import array
arr = array.array('i', [1, 2, 3, 4, 5])
# Using for loop
for item in arr:
print(item)
# Using while loop
i = 0
while i < len(arr):
print(arr[i])
i += 1
1
2
3
4
5
To copy an array, you can use the `copy()` method or the `array()` constructor.
# Copying Arrays
import array
arr = array.array('i', [1, 2, 3])
arr_copy = arr.copy() # Using copy() method
print(arr_copy)
array('i', [1, 2, 3])
To reverse an array, you can use the `reverse()` method, which reverses the array in place.
# Reversing Arrays
import array
arr = array.array('i', [1, 2, 3, 4, 5])
arr.reverse()
print(arr)
array('i', [5, 4, 3, 2, 1])
Arrays can be sorted using the `sort()` method, which sorts the elements in ascending order by default.
# Sorting Arrays
import array
arr = array.array('i', [5, 3, 4, 1, 2])
arr.sort()
print(arr)
array('i', [1, 2, 3, 4, 5])
To join multiple arrays, you can use the `extend()` method, which adds all items from one array to another.
# Joining Arrays
import array
arr1 = array.array('i', [1, 2, 3])
arr2 = array.array('i', [4, 5, 6])
arr1.extend(arr2)
print(arr1)
array('i', [1, 2, 3, 4, 5, 6])
Arrays in Python come with a variety of methods like `append()`, `insert()`, `remove()`, `pop()`, `reverse()`, and `sort()` that you can use to modify and manipulate the array.
# Array Methods Example
import array
arr = array.array('i', [1, 2, 3, 4])
arr.append(5) # Add an element at the end
arr.insert(2, 6) # Insert an element at index 2
arr.remove(3) # Remove the first occurrence of 3
print(arr)
array('i', [1, 2, 6, 4, 5])
Below are a couple of exercises that help you practice array manipulation in Python.
# Exercise 1: Add, remove, and print array items
import array
arr = array.array('i', [1, 2, 3, 4])
arr.append(5)
arr.remove(2)
print(arr)
# Exercise 2: Reverse and sort an array
arr = array.array('i', [5, 3, 4, 2, 1])
arr.reverse()
arr.sort()
print(arr)
array('i', [1, 3, 4, 5])
array('i', [1, 2, 3, 4, 5])
File handling in Python refers to the process of reading from and writing to files. Python provides built-in functions and methods to manipulate files on the filesystem.
In Python, you can write to a file using the `write()` or `writelines()` methods. The `open()` function is used to open a file, and then you can write to it.
# Writing to a file
file = open('example.txt', 'w') # 'w' stands for write mode
file.write("Hello, world!")
file.close()
A new file `example.txt` is created, and the text "Hello, world!" is written inside it.
To read from a file in Python, you can use the `read()`, `readline()`, or `readlines()` methods. The `open()` function is used in the read mode (`r`).
# Reading from a file
file = open('example.txt', 'r')
content = file.read()
print(content)
file.close()
Hello, world!
Python provides methods to rename and delete files using the `os` module. You can use `os.rename()` to rename a file and `os.remove()` to delete a file.
import os
# Renaming a file
os.rename('example.txt', 'new_example.txt')
# Deleting a file
os.remove('new_example.txt')
The file `example.txt` is renamed to `new_example.txt`, and then it is deleted.
In Python, directories can be created, removed, and listed using the `os` module. You can create a directory with `os.mkdir()` and remove it with `os.rmdir()`.
import os
# Creating a directory
os.mkdir('new_directory')
# Removing a directory
os.rmdir('new_directory')
A new directory `new_directory` is created and then removed.
Python file objects provide several methods to perform file operations. Common methods include `read()`, `write()`, `seek()`, `tell()`, and `close()`.
# File Methods Example
file = open('example.txt', 'w')
file.write("Hello, Python!")
file.seek(0) # Move cursor to the beginning
content = file.read()
print(content)
file.close()
Hello, Python!
The `os` module provides methods to interact with the operating system. You can use `os.path.exists()` to check if a file or directory exists, and `os.listdir()` to list all files in a directory.
import os
# Checking if a file exists
file_exists = os.path.exists('example.txt')
print(file_exists)
# Listing files in a directory
files = os.listdir('.')
print(files)
True
['example.txt', 'other_file.txt']
The `os.path` module contains various functions to work with file and directory paths. You can use `os.path.join()` to join paths, `os.path.abspath()` to get the absolute path, and `os.path.basename()` to get the base name of a file.
import os
# Joining paths
path = os.path.join('folder', 'file.txt')
print(path)
# Getting the absolute path
absolute_path = os.path.abspath('example.txt')
print(absolute_path)
# Getting the base name of a file
base_name = os.path.basename('/path/to/example.txt')
print(base_name)
folder/file.txt
/home/user/example.txt
example.txt
Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes for structuring code. It allows for more manageable, scalable, and reusable code.
In Python, a class is a blueprint for creating objects. An object is an instance of a class. Classes define methods and attributes that their objects will have.
# Example of a class and object
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
# Creating an object
person1 = Person("Alice", 30)
person1.greet()
Hello, my name is Alice and I am 30 years old.
Class attributes are variables that are shared by all instances of a class. They are defined inside the class but outside of any methods.
class Car:
wheels = 4 # class attribute
# Creating objects
car1 = Car()
car2 = Car()
print(car1.wheels)
print(car2.wheels)
4
4
Class methods are methods that are bound to the class rather than instances. They are defined using the `@classmethod` decorator.
class Example:
@classmethod
def greet(cls):
print("Hello, class method!")
# Calling the class method
Example.greet()
Hello, class method!
Static methods do not operate on an instance or the class. They are defined using the `@staticmethod` decorator.
class Example:
@staticmethod
def greet():
print("Hello, static method!")
# Calling the static method
Example.greet()
Hello, static method!
Constructors are special methods used to initialize the attributes of an object when it is created. In Python, the `__init__` method is the constructor.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# Creating an object with a constructor
person1 = Person("John", 25)
print(person1.name)
print(person1.age)
John
25
Python uses access modifiers like public, private, and protected to control the visibility of class attributes and methods. By default, attributes are public.
class Person:
def __init__(self, name):
self.name = name
self.__age = 30 # private attribute
def get_age(self):
return self.__age
# Creating an object
person = Person("Alice")
print(person.name)
print(person.get_age())
Alice
30
Inheritance allows one class to inherit the attributes and methods of another class. In Python, you can create a child class that inherits from a parent class.
class Animal:
def speak(self):
print("Animal is speaking")
class Dog(Animal):
def bark(self):
print("Dog is barking")
# Creating an object of the child class
dog = Dog()
dog.speak() # inherited method
dog.bark() # child class method
Animal is speaking
Dog is barking
Polymorphism allows a method to have different implementations based on the object calling it. It can be achieved through method overriding and method overloading.
class Animal:
def speak(self):
print("Animal is speaking")
class Dog(Animal):
def speak(self):
print("Dog is barking")
# Polymorphism in action
animal = Animal()
animal.speak()
dog = Dog()
dog.speak()
Animal is speaking
Dog is barking
Method overriding allows a child class to provide a specific implementation of a method that is already defined in its parent class.
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def speak(self):
print("Dog barks")
# Creating objects
animal = Animal()
dog = Dog()
animal.speak() # Parent class method
dog.speak() # Child class method
Animal speaks
Dog barks
Method overloading allows multiple methods with the same name but different parameters in the same class. Python does not directly support method overloading, but we can achieve it using default arguments.
class Greet:
def say_hello(self, name="World"):
print(f"Hello, {name}")
greeting = Greet()
greeting.say_hello()
greeting.say_hello("Alice")
Hello, World
Hello, Alice
Dynamic binding in Python means that method calls are resolved at runtime, allowing flexibility in the behavior of objects.
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def speak(self):
print("Dog barks")
# Dynamic binding
animal = Dog()
animal.speak()
Dog barks
Dynamic typing means that the type of a variable is determined at runtime. Variables are not bound to a fixed type in Python.
x = 5
print(type(x))
x = "Hello"
print(type(x))
<class 'int'>
<class 'str'>
Abstraction is the concept of hiding the complexity of a system and exposing only the necessary parts. It can be achieved using abstract classes and methods in Python.
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def speak(self):
pass
class Dog(Animal):
def speak(self):
print("Dog barks")
dog = Dog()
dog.speak()
Dog barks
Encapsulation is the concept of binding the data (attributes) and the methods that manipulate the data into a single unit, i.e., a class. It also involves controlling access to data using access modifiers.
class Account:
def __init__(self, balance):
self.__balance = balance # private attribute
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
acc = Account(1000)
acc.deposit(500)
print(acc.get_balance())
1500
Python does not have explicit interface classes like some other languages, but it can achieve similar functionality through abstract base classes (ABCs).
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def area(self):
return 3.14 * 5 ** 2
circle = Circle()
print(circle.area())
78.5
Packages in Python are namespaces containing multiple modules. They allow you to organize and manage code across multiple files.
# Example of using a package
import math
print(math.sqrt(16))
4.0
Inner classes are classes defined within another class. They can be useful for grouping related functionality together.
class Outer:
class Inner:
def message(self):
print("Hello from inner class")
outer = Outer()
inner = outer.Inner()
inner.message()
Hello from inner class
An anonymous class is a class created without a name, typically used for short-term use. It can be implemented using lambda functions or dynamically in Python.
obj = type("Person", (), {"name": "Alice", "age": 30})
print(obj.name)
print(obj.age)
Alice
30
A singleton class ensures that only one instance of a class is created and provides a global point of access to it.
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super(Singleton, cls).__new__(cls)
return cls._instance
obj1 = Singleton()
obj2 = Singleton()
print(obj1 is obj2)
True
Wrapper classes are used to wrap primitive data types into objects. In Python, this is rarely needed because Python has built-in support for dynamic types.
# Wrapping a primitive type into an object
x = 5
y = int(x) # Wrapping int into an object
print(type(y))
<class 'int'>
Enums are used to define a set of constant values. Python has an in-built `enum` module that helps to define them easily.
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
print(Color.RED)
print(Color.GREEN)
Color.RED
Color.GREEN
Reflection allows a program to inspect and modify its structure at runtime. Python provides functions such as `getattr()`, `setattr()`, and `hasattr()` for this purpose.
class Person:
def __init__(self, name):
self.name = name
p = Person("Alice")
print(getattr(p, "name"))
setattr(p, "name", "Bob")
print(getattr(p, "name"))
Alice
Bob
Errors in Python can be categorized into syntax errors and exceptions. While syntax errors occur when the parser detects incorrect Python syntax, exceptions are errors that occur during the execution of a program.
Syntax errors occur when the Python interpreter encounters code that doesn’t conform to valid syntax rules. These are caught before the program is executed.
# Example of Syntax Error
if True
print("Missing colon at the end of if statement")
SyntaxError: invalid syntax
Exceptions are errors detected during execution. Python has several built-in exceptions such as `ZeroDivisionError`, `ValueError`, and `TypeError`. These can be handled using the `try-except` block.
The `try` block allows you to test code for errors, and the `except` block handles the error if one occurs.
# Example of try-except block
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Cannot divide by zero
The `finally` block lets you execute code, regardless of whether an exception occurs or not.
# Example of try-finally block
try:
result = 10 / 0
finally:
print("This will always be executed")
This will always be executed
ZeroDivisionError: division by zero
You can raise exceptions in Python using the `raise` keyword. This is useful when you want to manually trigger an exception under certain conditions.
# Example of raising an exception
x = -1
if x < 0:
raise ValueError("Negative values are not allowed")
ValueError: Negative values are not allowed
Python allows you to chain exceptions using the `from` keyword, which helps in showing a relationship between exceptions.
# Example of exception chaining
try:
open("nonexistent_file.txt")
except FileNotFoundError as e:
raise RuntimeError("Failed to open file") from e
RuntimeError: Failed to open file
Caused by: FileNotFoundError: No such file or directory
You can use a `try-except` block inside another `try-except` block. This is called nested exception handling.
# Example of nested try-except block
try:
try:
result = 10 / 0
except ZeroDivisionError:
print("Caught inner division error")
except:
print("Caught outer error")
Caught inner division error
Python allows you to create your own custom exceptions by subclassing the `Exception` class.
# Example of user-defined exception
class CustomError(Exception):
pass
def check_value(value):
if value < 0:
raise CustomError("Value cannot be negative")
try:
check_value(-1)
except CustomError as e:
print(e)
Value cannot be negative
Logging is useful for tracking events that happen when some software runs. Python’s built-in `logging` module allows you to log messages at different levels (e.g., `DEBUG`, `INFO`, `ERROR`).
import logging
logging.basicConfig(level=logging.ERROR)
logging.error("This is an error message")
ERROR:root:This is an error message
Assertions are a way to test assumptions made by the program. If the assertion fails, Python raises an `AssertionError`.
# Example of assertion
x = 10
assert x > 5, "x should be greater than 5"
assert x < 5, "x should be less than 5" # This will raise AssertionError
AssertionError: x should be less than 5
Python has a rich set of built-in exceptions that help handle different error conditions. Some common built-in exceptions include `IndexError`, `KeyError`, `TypeError`, and `NameError`.
Multithreading is a technique where multiple threads execute independently but share the same resources. It is used to improve the performance of CPU-bound and I/O-bound tasks.
A thread in Python can go through various states during its life cycle: New, Runnable, Blocked, and Dead.
# Example of thread life cycle using threading module
import threading
import time
def thread_function():
print("Thread started")
time.sleep(2)
print("Thread finished")
# Creating and starting the thread
thread = threading.Thread(target=thread_function)
thread.start()
thread.join() # Wait for thread to complete before proceeding
Thread started
Thread finished
To create a thread in Python, you can use the `threading` module and pass the target function that will be executed by the thread.
# Example of creating a thread
import threading
def greet():
print("Hello from thread!")
# Creating a thread
thread = threading.Thread(target=greet)
thread.start() # Start the thread
thread.join() # Wait for the thread to finish
Hello from thread!
A thread starts execution when the `start()` method is called. This triggers the thread to execute its target function.
# Example of starting a thread
import threading
def print_numbers():
for i in range(5):
print(i)
# Creating and starting the thread
thread = threading.Thread(target=print_numbers)
thread.start() # Start the thread
0
1
2
3
4
The `join()` method is used to wait for a thread to complete before continuing the program's execution.
# Example of joining threads
import threading
import time
def print_message():
print("Thread is running")
time.sleep(2)
print("Thread finished")
thread = threading.Thread(target=print_message)
thread.start()
thread.join() # Wait for thread to finish before continuing
print("Main thread ends")
Thread is running
Thread finished
Main thread ends
You can assign a name to a thread for identification purposes. The name can be accessed and modified via the `name` attribute of a thread.
# Example of naming a thread
import threading
def task():
print("Thread is running")
thread = threading.Thread(target=task, name="CustomThreadName")
thread.start()
print(f"Thread Name: {thread.name}")
Thread is running
Thread Name: CustomThreadName
Python’s Global Interpreter Lock (GIL) controls the execution of threads. It ensures that only one thread runs at a time in a single process, which can affect the performance of multithreading in CPU-bound tasks.
A thread pool allows you to manage multiple threads more efficiently by reusing threads instead of creating new ones each time. Python’s `concurrent.futures` module provides a `ThreadPoolExecutor` to implement thread pooling.
# Example of using ThreadPoolExecutor
from concurrent.futures import ThreadPoolExecutor
def task(n):
print(f"Task {n} is running")
with ThreadPoolExecutor(max_workers=3) as executor:
for i in range(5):
executor.submit(task, i)
Task 0 is running
Task 1 is running
Task 2 is running
Task 3 is running
Task 4 is running
The main thread is the thread that starts when a Python program begins. Other threads are created as child threads of the main thread.
# Example of main thread
import threading
def worker():
print("Worker thread")
# Main thread starts here
thread = threading.Thread(target=worker)
thread.start()
thread.join() # Wait for worker thread to finish
Worker thread
Python does not natively support thread priorities. The `threading` module executes threads without any inherent priority mechanism, but you can implement custom priority logic in your threads.
Daemon threads are background threads that run independently of the main program. They are terminated as soon as the main program ends.
# Example of daemon thread
import threading
import time
def background_task():
while True:
print("Daemon thread running")
time.sleep(1)
daemon_thread = threading.Thread(target=background_task, daemon=True)
daemon_thread.start()
time.sleep(5) # Main thread runs for 5 seconds before terminating
Daemon thread running
Daemon thread running
Daemon thread running
Synchronization is crucial when multiple threads share data. Python’s `threading` module provides tools like locks, events, and conditions to synchronize threads and avoid race conditions.
# Example of thread synchronization using Lock
import threading
lock = threading.Lock()
def critical_section():
with lock:
print("Thread is in the critical section")
thread1 = threading.Thread(target=critical_section)
thread2 = threading.Thread(target=critical_section)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
Thread is in the critical section
Thread is in the critical section
Synchronization is a process that ensures that only one thread accesses a shared resource at a time. Python provides various mechanisms such as Locks, Semaphores, Events, and Conditions for thread synchronization.
# Example of synchronization using Lock
import threading
lock = threading.Lock()
def task():
with lock: # Locking the critical section
print("Thread has entered critical section")
# Create multiple threads
threads = [threading.Thread(target=task) for _ in range(5)]
for t in threads:
t.start()
for t in threads:
t.join()
Thread has entered critical section
Thread has entered critical section
Thread has entered critical section
Thread has entered critical section
Thread has entered critical section
Inter-thread communication allows threads to exchange data and synchronize with each other. Python provides `queue.Queue`, `threading.Event`, and other synchronization mechanisms for this purpose.
# Example of inter-thread communication using Queue
import threading
import queue
def producer(q):
for i in range(5):
q.put(i)
print(f"Produced: {i}")
def consumer(q):
while True:
item = q.get()
if item is None:
break
print(f"Consumed: {item}")
q = queue.Queue()
t1 = threading.Thread(target=producer, args=(q,))
t2 = threading.Thread(target=consumer, args=(q,))
t1.start()
t2.start()
t1.join()
q.put(None) # Signal the consumer thread to stop
t2.join()
Produced: 0
Consumed: 0
Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
Produced: 3
Consumed: 3
Produced: 4
Consumed: 4
A deadlock occurs when two or more threads are blocked forever, waiting for each other to release a resource. Python provides ways to avoid or handle deadlocks using timeout mechanisms and careful locking strategies.
# Example of deadlock scenario
import threading
lock1 = threading.Lock()
lock2 = threading.Lock()
def task1():
with lock1:
print("Task 1 acquired lock1")
with lock2:
print("Task 1 acquired lock2")
def task2():
with lock2:
print("Task 2 acquired lock2")
with lock1:
print("Task 2 acquired lock1")
t1 = threading.Thread(target=task1)
t2 = threading.Thread(target=task2)
t1.start()
t2.start()
t1.join()
t2.join() # This will cause a deadlock
Task 1 acquired lock1
Task 2 acquired lock2
Threads in Python can't be directly interrupted by the `threading` module, but you can design your thread to check periodically whether it should terminate. One common way to do this is by using a flag or an event object.
# Example of interrupting a thread using a flag
import threading
import time
def interruptible_task(flag):
while not flag.is_set():
print("Thread is running")
time.sleep(1)
print("Thread interrupted and stopped")
flag = threading.Event()
t = threading.Thread(target=interruptible_task, args=(flag,))
t.start()
time.sleep(3) # Let the thread run for a while
flag.set() # Set the event to interrupt the thread
t.join() # Wait for thread to finish
Thread is running
Thread is running
Thread is running
Thread interrupted and stopped
Python provides extensive support for networking through the `socket` module and higher-level libraries like `http.client`, `requests`, and more. Networking in Python involves creating client-server applications, sending data, and handling network protocols.
# Basic server-client example using socket
import socket
# Server code
def server():
s = socket.socket()
s.bind(('localhost', 12345))
s.listen(1)
print("Server is listening...")
conn, addr = s.accept()
print(f"Connection from {addr}")
conn.sendall(b"Hello from server")
conn.close()
# Client code
def client():
s = socket.socket()
s.connect(('localhost', 12345))
data = s.recv(1024)
print("Received from server:", data.decode())
s.close()
# To run the server and client, execute them in separate scripts or threads
Server is listening...
Connection from ('127.0.0.1', 12346)
Received from server: Hello from server
Socket programming in Python allows communication between computers over a network. A socket is an endpoint for sending or receiving data across a computer network.
# Simple echo server using socket
import socket
def echo_server():
s = socket.socket()
s.bind(('localhost', 65432))
s.listen(1)
print("Server waiting for connection...")
conn, addr = s.accept()
print(f"Connection established with {addr}")
while True:
data = conn.recv(1024)
if not data:
break
print(f"Received: {data.decode()}")
conn.sendall(data) # Echoing back the received message
conn.close()
def echo_client():
s = socket.socket()
s.connect(('localhost', 65432))
message = "Hello, Server!"
s.sendall(message.encode())
data = s.recv(1024)
print(f"Received from server: {data.decode()}")
s.close()
# Run the server and client in separate processes or scripts
Server waiting for connection...
Connection established with ('127.0.0.1', 12345)
Received: Hello, Server!
Received from server: Hello, Server!
URL processing in Python is done using modules like `urllib` and `requests`. These modules allow parsing, retrieving, and handling URLs and their components.
# URL parsing using urllib
from urllib.parse import urlparse
url = "http://www.example.com:8080/path?query=python#fragment"
parsed_url = urlparse(url)
print(f"Scheme: {parsed_url.scheme}")
print(f"Netloc: {parsed_url.netloc}")
print(f"Path: {parsed_url.path}")
print(f"Params: {parsed_url.params}")
print(f"Query: {parsed_url.query}")
print(f"Fragment: {parsed_url.fragment}")
Scheme: http
Netloc: www.example.com:8080
Path: /path
Params:
Query: query=python
Fragment: fragment
Generics in Python are typically used with type hints and function definitions to specify that certain parts of code (like functions or classes) can handle multiple data types. Python uses `typing` for generics to provide type flexibility while maintaining readability and functionality.
# Example of generics in Python using typing
from typing import TypeVar, Generic
T = TypeVar('T')
class Box(Generic[T]):
def __init__(self, value: T):
self.value = value
def get_value(self) -> T:
return self.value
# Box with an integer
box_int = Box(123)
print(box_int.get_value()) # Output: 123
# Box with a string
box_str = Box("Hello")
print(box_str.get_value()) # Output: Hello
123
Hello
Python has a rich set of libraries that make it an extremely powerful tool for various tasks such as data analysis, machine learning, scientific computing, web development, and computer vision.
NumPy is a core library for numerical computing in Python. It provides support for arrays, matrices, and a wide range of mathematical functions to operate on these data structures.
# Example of using NumPy to create an array and perform operations
import numpy as np
# Create a NumPy array
arr = np.array([1, 2, 3, 4, 5])
# Perform mathematical operations
arr_squared = arr ** 2
arr_sum = arr.sum()
print("Array:", arr)
print("Squared Array:", arr_squared)
print("Sum of Array:", arr_sum)
Array: [1 2 3 4 5]
Squared Array: [ 1 4 9 16 25]
Sum of Array: 15
Pandas is a powerful data manipulation and analysis library. It provides data structures like Series and DataFrame to handle structured data efficiently.
# Example of using Pandas to create a DataFrame and manipulate data
import pandas as pd
# Create a simple DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [24, 27, 22]}
df = pd.DataFrame(data)
# Display DataFrame
print(df)
# Perform basic operations
mean_age = df['Age'].mean()
print("Mean Age:", mean_age)
Name Age 0 Alice 24 1 Bob 27 2 Charlie 22
Mean Age: 24.33
SciPy is a scientific computing library that builds on NumPy. It provides additional functionality like optimization, integration, interpolation, eigenvalue problems, and more.
# Example of using SciPy for optimization
from scipy import optimize
# Define a function to minimize
def func(x):
return x ** 2 + 5
# Find the minimum of the function
result = optimize.minimize(func, 0)
print("Minimum of function:", result.fun)
Minimum of function: 5.0
Matplotlib is a popular library for data visualization in Python. It provides tools for creating static, animated, and interactive visualizations.
# Example of creating a simple plot using Matplotlib
import matplotlib.pyplot as plt
# Data for the plot
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
# Create a plot
plt.plot(x, y)
# Add labels and title
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.title("Simple Plot")
# Display the plot
plt.show()
The code will generate a plot of the equation y = x^2, with the X and Y axes labeled accordingly.
Django is a high-level web framework for Python that allows you to quickly develop secure and scalable web applications.
# Example of a basic Django view
from django.http import HttpResponse
from django.shortcuts import render
def hello_world(request):
return HttpResponse("Hello, World!")
The Django view will return "Hello, World!" when accessed through a browser.
OpenCV (Open Source Computer Vision) is a library that provides tools for real-time computer vision. It helps with image processing, face recognition, and other advanced features.
# Example of reading and displaying an image using OpenCV
import cv2
# Read an image
image = cv2.imread('image.jpg')
# Display the image in a window
cv2.imshow('Image', image)
# Wait for a key press and close the window
cv2.waitKey(0)
cv2.destroyAllWindows()
The code will open an image file ('image.jpg') and display it in a window.
Python offers a variety of built-in features and libraries that allow you to handle different tasks like date/time operations, recursion, decorators, regular expressions, working with databases, and more.
Python has a built-in module called `datetime` that helps you handle dates and times effectively.
# Example of using the datetime module
import datetime
# Get the current date and time
now = datetime.datetime.now()
# Display the current date and time
print("Current Date and Time:", now)
Current Date and Time: 2024-11-22 14:30:15.675423
Python provides a built-in `math` module that includes mathematical functions such as trigonometric functions, logarithms, and more.
# Example of using the math module
import math
# Calculate square root
sqrt_val = math.sqrt(16)
# Calculate the factorial of a number
factorial_val = math.factorial(5)
print("Square Root:", sqrt_val)
print("Factorial:", factorial_val)
Square Root: 4.0
Factorial: 120
Iterators are objects in Python that represent a stream of data. Python provides the `iter()` function to get an iterator from an iterable object.
# Example of using iterators
my_list = [1, 2, 3, 4]
# Get an iterator from the list
iterator = iter(my_list)
# Iterate through the elements using next()
print(next(iterator))
print(next(iterator))
1
2
Generators are special types of iterators in Python. They are defined using a function with the `yield` keyword.
# Example of using a generator function
def count_up_to(n):
count = 1
while count <= n:
yield count
count += 1
# Create a generator object
counter = count_up_to(5)
# Iterate through the generator
for number in counter:
print(number)
1
2
3
4
5
A closure in Python is a function that remembers its lexical scope even when the function is called outside that scope.
# Example of using closures
def outer_function(x):
def inner_function(y):
return x + y
return inner_function
closure = outer_function(5)
result = closure(10) # It remembers the value of x (5)
print(result)
15
Decorators are functions that modify the behavior of another function. They are applied using the `@` syntax.
# Example of using a decorator
def decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
@decorator
def hello():
print("Hello, World!")
hello()
Before function call
Hello, World!
After function call
Recursion is the process of a function calling itself. It is commonly used for tasks that can be divided into smaller subproblems.
# Example of using recursion to calculate factorial
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(5))
120
Regular expressions allow you to search for patterns in strings. Python provides the `re` module to work with regular expressions.
# Example of using regular expressions
import re
# Search for a pattern in a string
pattern = r'\d+'
text = "There are 10 apples"
matches = re.findall(pattern, text)
print(matches)
['10']
PIP (Python Package Index) is a package manager for Python that allows you to install and manage Python libraries.
# To install a library using pip
# Run this command in your terminal
pip install numpy
Python provides various libraries to interact with databases, such as `sqlite3`, `MySQLdb`, and `psycopg2` for PostgreSQL.
# Example of accessing SQLite database
import sqlite3
# Connect to the database
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
# Create a table and insert data
cursor.execute('''CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)''')
cursor.execute("INSERT INTO users (name) VALUES ('Alice')")
# Commit and close the connection
conn.commit()
conn.close()
Weak references allow you to refer to an object without preventing it from being garbage collected.
# Example of using weak references
import weakref
class MyClass:
def __del__(self):
print("Object deleted")
obj = MyClass()
weak_ref = weakref.ref(obj)
print(weak_ref())
del obj
print(weak_ref())
Serialization is the process of converting an object into a byte stream. Python provides the `pickle` module to serialize and deserialize objects.
# Example of using pickle for serialization
import pickle
data = {'name': 'Alice', 'age': 25}
# Serialize data
with open('data.pickle', 'wb') as file:
pickle.dump(data, file)
# Deserialize data
with open('data.pickle', 'rb') as file:
loaded_data = pickle.load(file)
print(loaded_data)
Templating is used to create dynamic HTML pages. Python has various libraries like `Jinja2` that allow for this functionality.
# Example of using Jinja2 for templating
from jinja2 import Template
template = Template("Hello, {{ name }}!")
rendered = template.render(name="Alice")
print(rendered)
Python allows you to format your output easily using f-strings, `str.format()`, or the `%` operator.
# Example of using f-strings
name = "Alice"
age = 25
print(f"Name: {name}, Age: {age}")
You can measure the performance of your Python code using the `time` module or more advanced tools like `timeit`.
# Example of measuring performance with time module
import time
start_time = time.time()
# Some code to measure
time.sleep(2)
end_time = time.time()
print(f"Execution Time: {end_time - start_time} seconds")
Python provides libraries like `zlib` and `gzip` for data compression and decompression.
# Example of using zlib for compression
import zlib
data = b"Hello World! " * 100
compressed_data = zlib.compress(data)
print("Compressed Data:", compressed_data)
Common Gateway Interface (CGI) allows Python to interact with web servers and generate dynamic content.
# Example of a simple CGI script
#!/usr/bin/env python
import cgi
form = cgi.FieldStorage()
name = form.getvalue("name")
print("Content-type: text/html\n")
print(f"Hello, {name}
")
Python provides libraries like `xml.etree.ElementTree` and `minidom` to work with XML files.
# Example of parsing XML with ElementTree
import xml.etree.ElementTree as ET
data = "Alice 25 "
root = ET.fromstring(data)
name = root.find("name").text
print(name)
Python provides libraries like `Tkinter`, `PyQt`, and `wxPython` for creating graphical user interfaces.
# Example of a basic Tkinter window
import tkinter as tk
root = tk.Tk()
root.title("Simple Window")
label = tk.Label(root, text="Hello, World!")
label.pack()
root.mainloop()
Python allows you to handle command-line arguments using the `sys.argv` or `argparse` module.
# Example of using sys.argv
import sys
print("Script Name:", sys.argv[0])
print("Arguments:", sys.argv[1:])
Docstrings are used to document Python functions, classes, and modules. They are written in triple quotes.
# Example of a function with docstring
def greet(name):
"""This function greets the person passed in as a parameter"""
print(f"Hello, {name}")
print(greet.__doc__)
JSON (JavaScript Object Notation) is commonly used for data interchange. Python provides the `json` module to work with JSON data.
# Example of working with JSON
import json
data = {"name": "Alice", "age": 25}
# Convert Python object to JSON string
json_string = json.dumps(data)
# Convert JSON string back to Python object
data_parsed = json.loads(json_string)
print(data_parsed)
You can send emails using Python's `smtplib` library to interact with SMTP servers.
# Example of sending an email
import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login("your_email@gmail.com", "your_password")
server.sendmail("from_email@example.com", "to_email@example.com", "Subject: Test\n\nThis is a test email.")
server.quit()
Python offers many further extensions that you can use for specific tasks, such as image processing, machine learning, and more.
Python provides several built-in tools for various utilities like debugging, profiling, and more.
Graphical User Interfaces (GUIs) can be created in Python using libraries like Tkinter and PyQt to create desktop applications.
Abstract Base Classes (ABCs) in Python provide a way to define abstract methods that must be implemented by any subclass. They are defined in the abc
module.
from abc import ABC, abstractmethod
class MyClass(ABC):
@abstractmethod
def my_method(self):
pass
class DerivedClass(MyClass):
def my_method(self):
return "Method implemented!"
Method implemented!
Python allows you to create your own exceptions by subclassing the built-in Exception
class.
class CustomError(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
try:
raise CustomError("Something went wrong!")
except CustomError as e:
print(e)
Something went wrong!
Higher-order functions are functions that can take other functions as arguments or return functions as results. Examples include map
, filter
, and reduce
.
def apply_function(func, value):
return func(value)
result = apply_function(lambda x: x * 2, 5)
print(result) # Output: 10
10
Python objects are implemented as dictionaries, where the keys are the attributes or methods of the object. Understanding Python's object internals can help you optimize performance.
class MyClass:
def __init__(self):
self.x = 10
obj = MyClass()
print(obj.__dict__) # Output: {'x': 10}
{'x': 10}
Python uses automatic memory management, involving garbage collection for reclaiming unused memory. You can interact with the memory using modules like gc
and sys
.
import gc
# Triggering garbage collection
gc.collect()
Metaclasses are classes for classes. They define how classes themselves are constructed. In most cases, Python automatically handles metaclasses, but you can customize them for advanced use cases.
class MyMeta(type):
def __new__(cls, name, bases, dct):
print(f"Creating class {name}")
return super().__new__(cls, name, bases, dct)
class MyClass(metaclass=MyMeta):
pass
Creating class MyClass
Metaprogramming in Python allows you to manipulate code structure. You can use metaclasses to dynamically create or alter classes during runtime.
class Meta(type):
def __new__(cls, name, bases, dct):
dct['new_attribute'] = 'Added dynamically'
return super().__new__(cls, name, bases, dct)
class MyClass(metaclass=Meta):
pass
print(MyClass.new_attribute) # Output: Added dynamically
Added dynamically
Mocking and stubbing are techniques used in unit testing to simulate objects or functions and control their behavior. The unittest.mock
library is commonly used for these purposes.
from unittest.mock import MagicMock
mock = MagicMock()
mock.method.return_value = 'mocked value'
print(mock.method()) # Output: mocked value
mocked value
Monkey patching involves modifying or extending modules or classes at runtime, often for testing or adding new functionality without altering the original code.
import math
# Monkey patching the math module
def new_sqrt(x):
return 42
math.sqrt = new_sqrt
print(math.sqrt(16)) # Output: 42
42
Python allows handling system signals, such as interrupt or termination signals, using the signal
module. You can define custom handlers for these signals.
import signal
import time
def handler(signum, frame):
print("Signal received!")
signal.signal(signal.SIGINT, handler)
print("Waiting for signal...")
time.sleep(5)
Type hints allow you to specify expected types of function arguments and return values, improving code readability and enabling better static analysis.
def add_numbers(a: int, b: int) -> int:
return a + b
print(add_numbers(5, 10)) # Output: 15
15
Python is often used for automating repetitive tasks. You can use modules like os
, shutil
, and subprocess
to automate file manipulation, system tasks, and more.
import os
# Renaming a file
os.rename('old_file.txt', 'new_file.txt')
The humanize
package provides easy-to-read representations of data, such as times, numbers, and file sizes.
import humanize
print(humanize.naturalsize(1024)) # Output: 1.0 kB
1.0 kB
Context managers allow you to manage resources efficiently, such as opening and closing files, using the with
statement. They can be implemented using __enter__
and __exit__
methods.
class MyContextManager:
def __enter__(self):
print("Entering the context")
return self
def __exit__(self, exc_type, exc_value, traceback):
print("Exiting the context")
with MyContextManager() as cm:
print("Inside the context")
Entering the context
Inside the context
Exiting the context
Coroutines are special types of functions that allow pausing
Get commonly asked Python questions and answers, ranging from basic to advanced levels, covering various Python topics like syntax, libraries, and concepts.
Test your Python knowledge with an online quiz covering essential Python concepts like data structures, algorithms, and functions.
A quick guide to Python programming that covers the basics, syntax, and important topics in a concise format for beginners.
The Python Reference provides detailed explanations of Python's syntax, libraries, and built-in functions to help developers understand how each feature works.
A handy Python cheatsheet that summarizes key Python commands, functions, and syntax to help you quickly look up information while coding.
Python project ideas for beginners and advanced learners, including real-world applications like web development, data science, automation, and more.
Find useful Python resources, including tutorials, documentation, books, and community forums to enhance your learning experience.
Join Python discussion forums to connect with other learners, ask questions, share knowledge, and get insights from experienced developers.
An online Python compiler allows you to write, compile, and run Python code in your browser without needing to install any software.
The NumPy compiler is an online tool for writing and executing Python code that uses the NumPy library for numerical computations and array manipulations.
The Matplotlib compiler allows you to create and run Python code that generates visualizations like plots and graphs using the Matplotlib library.
The SciPy compiler is an online platform for executing Python code that leverages the SciPy library for scientific and technical computing tasks.
Comprehensive notes for the UPSC IAS exams, covering various subjects like history, geography, politics, and current affairs to help candidates in their exam preparation.
A collection of coding and software development best practices to ensure code quality, maintainability, and efficiency for developers.
A set of frequently asked questions and their answers across various domains, including programming, general knowledge, and technical subjects.
Guidelines and tips for writing an effective resume that stands out to potential employers, with examples and templates for different fields.
Common HR interview questions with sample answers to help candidates prepare for job interviews and understand what interviewers look for.
A glossary of computer-related terms and definitions, helping both beginners and advanced users to better understand technical jargon.
A guide to important personalities and their roles in various fields such as politics, science, literature, and more.
Output:
5