1. Python HOME
Python is a user friendly programming language used for various purposes like web development, data analysis, machine learning, and more.
print("Welcome to Python!")
Welcome to Python!
2. Python Intro
Python is easy to learn and has a simple syntax that makes coding more intuitive and enjoyable.
print("Python is fun!")
Python is fun!
3. Python Get Started
To start with Python, download and install Python from its official website: python.org.
print("Let's get started with Python!")
Let's get started with Python!
4. Python Syntax
Python syntax is straightforward and easy to understand. Indentation is crucial in Python.
if 5 > 2:
print("Five is greater than two!")
Five is greater than two!
Some examples
Python syntax refers to the set of rules that defines how Python code is written. It's important to follow these rules to make sure the code runs correctly.
1.1. Python Indentation
In Python, indentation is used to define the structure of the code. Unlike other languages that use curly braces, Python uses indentation to separate blocks of code.
print("Hello, World!")
greet()
Explanation: In the above code, the print()
function is inside the greet()
function, which is defined with indentation.
1.2. Python Variables
A variable in Python is a name that refers to a value. Variables are created when they are first assigned a value.
y = 20
sum = x + y
print(sum)
Explanation: The variables x
, y
, and sum
store values, and their sum is printed.
1.3. Python Comments
Comments are used to explain code. They are ignored by the Python interpreter and are useful for documentation.
print("This is a comment-free code.")
Explanation: The line starting with #
is a comment and doesn't affect the program's execution.
1.4. Python Data Types
Python has various data types including integers, floats, strings, and booleans.
y = 5.5 # float
name = "John" # string
is_valid = True # boolean
print(type(x))
print(type(y))
print(type(name))
print(type(is_valid))
Explanation: Each variable has a type which is identified using the type()
function.
1.5. Python Statements
Statements in Python are instructions that Python executes, such as assignments or function calls.
print("Hello!") # function call statement
Explanation: Both =
and print()
are statements in Python.
5. Python Comments
Comments in Python can be added using the hash symbol (#). They help make the code more readable.
print("Hello, World!")
Hello, World!
6. Python Variables
Variables are containers for storing data values. In Python, you don’t need to declare the type of variable explicitly.
x = 5
y = "Hello, Python!"
print(x)
print(y)
5
Hello, Python!
In Python, a variable is used to store data values. Unlike many other programming languages, Python doesn't require explicit declaration of variable types.
2.1. Declaring Variables
In Python, variables are created the moment you assign a value to them. You don’t need to specify their data type.
name = "Alice" # string variable
is_valid = True # boolean variable
print(x)
print(name)
print(is_valid)
Alice
True
Explanation: The variables x
, name
, and is_valid
are created and assigned values without needing to declare their types.
2.2. Rules for Variable Declaration
Here are the basic rules for declaring variables in Python:
- Variable names must start with a letter (A-Z or a-z) or an underscore (_).
- Variable names can contain letters, numbers, and underscores.
- Variable names are case-sensitive (e.g.,
myVar
andmyvar
are different variables). - A variable name cannot be a Python keyword (like
print
,if
, etc.). - Variable names should not start with a number.
2.3. Examples of Valid and Invalid Variable Names
Here are examples of valid and invalid variable names in Python:
my_variable = 5
_name = "John"
var123 = 10
# Invalid variable names:
123var = 20 # starts with a number
my-var = "Hello" # contains a hyphen
def = 30 # Python keyword
Explanation: In the valid variable names section, all names follow the rules. In the invalid section, variables break one of the rules, such as starting with a number or using a Python keyword.
2.4. Reassigning Values to Variables
In Python, variables can be reassigned new values at any time. You can change the data type of a variable as well.
print(x)
x = "Hello" # now a string
print(x)
Hello
Explanation: Initially, x
holds an integer. Then, it is reassigned a string value. This is allowed in Python.
2.5. Multiple Variable Assignment
You can assign values to multiple variables in one line.
print(a)
print(b)
print(c)
10
15
Explanation: The variables a
, b
, and c
are assigned values in a single line, which is an efficient way to declare and initialize multiple variables.
7. Python Data Types
Python has various data types like int, float, str, list, tuple, and more. You can check the type of a variable using the `type()` function.
x = 5 # int
y = 2.5 # float
z = "Hello" # str
print(type(x))
print(type(y))
print(type(z))
<class 'int'>
<class 'float'>
<class 'str'>
Some examples
Python supports several data types that are used to store different kinds of data. Below are the main data types in Python along with examples:
Data Type | Example |
---|---|
Integer | x = 10 |
Float | y = 3.14 |
String | name = "Alice" |
Boolean | is_valid = True |
List | numbers = [1, 2, 3] |
Tuple | coordinates = (4, 5) |
Set | colors = {"red", "green", "blue"} |
Dictionary | person = {"name": "John", "age": 25} |
Explanation: The table above shows some common data types in Python with examples. Each data type stores a specific kind of value:
- Integer: Stores whole numbers.
- Float: Stores decimal numbers.
- String: Stores text or sequences of characters.
- Boolean: Stores
True
orFalse
. - List: A collection of items in a particular order.
- Tuple: A collection of items, but immutable (unchangeable).
- Set: An unordered collection of unique items.
- Dictionary: A collection of key-value pairs.
8. Python Numbers
Python supports integers, floating-point numbers, and complex numbers.
x = 10
y = 3.14
z = 1j
print(x, y, z)
10 3.14 1j
9. Python Casting
Python allows you to cast values to a specific type, such as int, float, or str.
x = int(3.5)
y = str(10)
print(x)
print(y)
3
10
Casting in Python refers to the conversion of one data type to another. Python allows you to convert from one data type to another using built-in functions.
Types of Python Casting
There are mainly three types of casting in Python:
- Implicit Casting (Automatic Type Conversion)
- Explicit Casting (Manual Type Conversion)
- Type Conversion Functions
1. Implicit Casting (Automatic Type Conversion)
In Implicit Casting, Python automatically converts one data type to another without any explicit instruction from the programmer. This is usually done when a smaller data type is assigned to a larger data type.
y = 3.2 # Float
result = x + y # Python converts x to float
print(result)
Explanation: Here, the integer x
is automatically converted to a float before performing the addition with y
.
2. Explicit Casting (Manual Type Conversion)
Explicit casting is done manually by the programmer. Python provides functions to explicitly convert one type to another.
y = int(x) # Explicitly converting float to integer
print(y)
Explanation: The int()
function is used to convert the float x
to an integer.
3. Type Conversion Functions
Python provides several functions for type conversion, including:
int()
: Converts to an integer.float()
: Converts to a float.str()
: Converts to a string.list()
: Converts to a list.tuple()
: Converts to a tuple.set()
: Converts to a set.
10. Python - Unicode System
Python supports Unicode, which allows handling text in many languages.
text = "Hello, World!" # This is a Unicode string
print(text) # Prints: Hello, World!
11. Python - Literals
Literals are values used directly in the code.
num = 10
# String literal
name = "John"
# Float literal
price = 19.99
print(num, name, price)
12. Python - Operators
Operators perform operations on variables and values.
a = 5
b = 3
sum = a + b # Addition
print(sum)
13. Python Arithmetic Operators
These operators perform mathematical operations like addition, subtraction, multiplication, etc.
a = 10
b = 2
add = a + b
sub = a - b
mul = a * b
div = a / b
print(add, sub, mul, div)
14. Python Comparison Operators
These operators compare two values and return a boolean result.
a = 5
b = 3
print(a == b) # Equal
print(a != b) # Not equal
print(a > b) # Greater than
15. Python Assignment Operators
These operators are used to assign values to variables.
a = 10
a += 5 # a = a + 5
a -= 2 # a = a - 2
print(a)
16. Python - Logical Operators
Logical operators are used to combine conditional statements.
a = True
b = False
print(a and b) # Logical AND
print(a or b) # Logical OR
print(not a) # Logical NOT
17. Python - Bitwise Operators
Bitwise operators perform bit-level operations on integers.
a = 5 # 0101 in binary
b = 3 # 0011 in binary
print(a & b) # AND
print(a | b) # OR
print(a ^ b) # XOR
18. Python Membership Operators
Membership operators test if a value is a member of a sequence (such as a list, string, or tuple).
a = [1, 2, 3, 4, 5]
print(3 in a) # True, because 3 is in the list
print(6 not in a) # True, because 6 is not in the list
19. Python Identity Operators
Identity operators compare the memory location of two objects.
a = [1, 2, 3]
b = [1, 2, 3]
print(a is b) # False, because a and b have different memory locations
print(a == b) # True, because a and b have the same content
20. Python - Operator Precedence
Operator precedence determines the order in which operations are performed in an expression.
result = 5 + 2 * 3
print(result) # Multiplied first, then added, so 5 + (2 * 3) = 11
21. Python - Comments
Comments are used to explain the code and are not executed.
print("Hello, World!") # This prints a message
22. Python - User Input
The input()
function is used to take input from the user.
name = input("Enter your name: ")
print("Hello, " + name)
Hello, John
23. Python Numbers
Python supports various number types like integers, floats, and complex numbers.
a = 10 # Integer
b = 5.5 # Float
c = 3 + 4j # Complex number
print(a, b, c)
24. Python - Booleans
Booleans are a data type that can only have one of two values: True or False.
a = True
b = False
print(a and b) # False, because both need to be True
print(a or b) # True, because one is True
print(not a) # False, because a is True
25. Python Control Statements
Control statements in Python allow you to control the flow of execution.
a = 5
if a > 3:
print("a is greater than 3") # This will be printed
26. Python Control Flow
Control flow determines the order in which statements are executed in a program.
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
27. Python - Decision Making
Decision-making statements are used to execute certain statements based on conditions.
age = 20
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
28. Python If Statement
The if
statement is used to test a condition and execute code if the condition is True.
num = 10
if num > 5:
print("Number is greater than 5")
29. Python If else
The if-else
statement provides two blocks of code, one for when the condition is True and one for when it is False.
num = 3
if num > 5:
print("Greater than 5")
else:
print("Less than or equal to 5")
30. Python - Nested If
A nested if
statement is an if
statement inside another if
statement.
num = 10
if num > 5:
if num < 15:
print("Number is between 5 and 15")
31. Python Match-Case Statement
The match-case
statement allows pattern matching and is used in Python 3.10 and above.
value = 2
match value:
case 1:
print("One")
case 2:
print("Two")
case _:
print("Other")
32. Python - Loops
Loops are used to execute a block of code multiple times based on a condition.
for i in range(5):
print(i)
1
2
3
4
33. Python - for Loops
The for
loop is used to iterate over a sequence like a list or range.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
banana
cherry
34. Python - for-else Loops
The for-else
loop executes the else
block only if the loop is not terminated by a break
statement.
for i in range(3):
print(i)
else:
print("For loop completed without break")
1
2
For loop completed without break
35. Python - While Loops
The while
loop runs as long as the given condition is True.
count = 0
while count < 3:
print(count)
count += 1
1
2
36. Python - break Statement
The break
statement is used to exit the loop prematurely.
for i in range(5):
if i == 3:
break
print(i)
1
2
37. Python continue Statement
The continue
statement is used to skip the current iteration of the loop and proceed to the next iteration.
for i in range(5):
if i == 3:
continue
print(i)
1
2
4
38. Python pass Statement
The pass
statement is used as a placeholder for future code and does nothing.
for i in range(5):
if i == 3:
pass # Do nothing
print(i)
1
2
3
4
39. Python - Nested Loops
A nested loop is a loop inside another loop, allowing for more complex iterations.
for i in range(2):
for j in range(3):
print(f"i={i}, j={j}")
i=0, j=1
i=0, j=2
i=1, j=0
i=1, j=1
i=1, j=2
40. Python Functions & Modules
Functions allow you to encapsulate code into reusable blocks, while modules are files containing functions and variables for reuse.
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
41. Python - Functions
A function is a block of code that only runs when it is called.
def say_hello():
print("Hello!")
say_hello()
42. Python - Default Arguments
Functions can have default values for arguments, which are used if no value is provided.
def greet(name="User"):
return f"Hello, {name}"
print(greet()) # Uses default argument
print(greet("Alice")) # Uses provided argument
Hello, Alice
43. Python - Keyword Arguments
Keyword arguments allow you to pass arguments by explicitly mentioning the parameter name.
def greet(name, age):
return f"{name} is {age} years old."
print(greet(name="Alice", age=25))
44. Python - Keyword-Only Arguments
Keyword-only arguments must be passed using their names and cannot be given positionally.
def greet(name, /, age):
return f"{name} is {age} years old." # 'name' is positional, 'age' is keyword-only
print(greet("Alice", age=25))
45. Python - Positional Arguments
Positional arguments are passed in the correct order according to the function's parameters.
def greet(name, age):
return f"{name} is {age} years old."
print(greet("Alice", 25))
46. Python - Positional-Only Arguments
Positional-only arguments must be passed by position and cannot be passed as keyword arguments.
def greet(name, /, age):
return f"{name} is {age} years old." # 'name' is positional-only
print(greet("Alice", 25))
47. Python - Arbitrary Arguments
Arbitrary arguments allow you to pass a variable number of arguments to a function using *args
or **kwargs
.
def greet(*names):
return f"Hello, {' and '.join(names)}!"
print(greet("Alice", "Bob", "Charlie"))
48. Python - Variables Scope
Variable scope defines the area in which a variable can be accessed. Variables can be local, global, or nonlocal.
x = 10 # Global variable
def example_function():
x = 5 # Local variable
print(x) # Local variable is printed example_function()
print(x) # Global variable is printed
10
49. Python - Function Annotations
Function annotations provide a way to add metadata to the parameters and return type of a function.
def greet(name: str, age: int) -> str:
return f"{name} is {age} years old." # Type annotations for parameters and return type print(greet("Alice", 25))
50. Python - Modules
Modules allow you to organize and reuse code. You can import modules to use their functions and variables.
import math
print(math.sqrt(16)) # Using math module to calculate square root
51. Python - Built-in Functions
Python provides a set of built-in functions that you can use without needing to import any modules.
numbers = [1, 2, 3, 4]
print(sum(numbers)) # Built-in sum() function calculates sum of elements
52. Python Strings
Strings are sequences of characters enclosed in quotes. They are one of the most common data types in Python.
name = "Hello, World!"
print(name)
53. Python - Slicing Strings
Slicing allows you to extract a portion of a string using a specific range of indices.
name = "Hello, World!"
print(name[7:12]) # Slicing from index 7 to 12
54. Python Modify Strings
Strings in Python are immutable, but you can modify them by creating new strings using string operations.
name = "hello"
name = name.capitalize() # Capitalizing the first letter
print(name)
55. Python String Concatenation
String concatenation is the process of joining two or more strings together.
first_name = "Alice"
last_name = "Smith"
full_name = first_name + " " + last_name # Concatenating strings
print(full_name)
56. Python - String Formatting
String formatting allows you to insert variables into strings in a readable way.
name = "Alice"
age = 25
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)
57. Python - Escape Characters
Escape characters allow you to include special characters like newlines, tabs, and quotes in strings.
string_with_quotes = "She said, \"Hello!\""
string_with_newline = "Hello\nWorld!"
print(string_with_quotes)
print(string_with_newline)
Hello
World!
58. Python - String Methods
Python provides various built-in methods that allow you to manipulate and perform operations on strings.
text = "hello world"
print(text.upper()) # Converts to uppercase
print(text.replace("world", "Alice")) # Replaces part of the string
hello Alice
59. Python - String Exercises
Exercises on strings help you practice and improve your understanding of string operations in Python.
text = "Python programming"
print(text[0:6]) # Extracts first 6 characters
print(text[-11:]) # Extracts last 11 characters
programming
60. Python Lists
Lists are ordered collections of elements that can be of any data type.
fruits = ["apple", "banana", "cherry"]
print(fruits)
61. Python - Access List Items
List items can be accessed using their index values, starting from 0 for the first element.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Accessing the first element
print(fruits[1]) # Accessing the second element
banana
62. Python - Change List Items
List items can be changed by assigning a new value to the specific index of the list.
fruits = ["apple", "banana", "cherry"]
fruits[1] = "orange" # Changing second item
print(fruits)
63. Python - Remove List Items
List items can be removed using various methods like remove(), pop(), or del.
fruits = ["apple", "banana", "cherry"]
fruits.remove("banana") # Removing a specific item
print(fruits)
64. Python - Loop Lists
Lists can be looped through using a for loop to access each element.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
banana
cherry
65. Python - List Comprehension
List comprehension provides a concise way to create lists based on existing lists.
numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers] # Creating a list of squares
print(squares)
66. Python - Sort Lists
Lists can be sorted using the sort() method to arrange elements in ascending or descending order.
fruits = ["banana", "apple", "cherry"]
fruits.sort() # Sorting in ascending order
print(fruits)
67. Python - Copy Lists
You can create a copy of a list using the copy() method or the list slicing technique.
fruits = ["apple", "banana", "cherry"]
new_fruits = fruits.copy() # Using copy() method
print(new_fruits)
68. Python - Join Lists
You can join two lists using the + operator or the extend() method.
list1 = ["apple", "banana"]
list2 = ["cherry", "date"]
joined_list = list1 + list2 # Using + operator to join
print(joined_list)
69. Python - List Methods
Python provides various built-in methods to manipulate lists, such as append(), insert(), and remove().
fruits = ["apple", "banana", "cherry"]
fruits.append("date") # Adding an item to the end
fruits.insert(1, "orange") # Inserting an item at a specific index
fruits.remove("banana") # Removing an item by value
print(fruits)
70. Python - List Exercises
List exercises help you practice and improve your understanding of list operations in Python.
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
fruits.insert(2, "kiwi")
fruits.remove("banana")
print(fruits)
71. Python Tuples
Tuples are immutable sequences, typically used to store collections of heterogeneous data.
fruits = ("apple", "banana", "cherry")
print(fruits)
72. Python - Access Tuple Items
Tuple items can be accessed using their index values, starting from 0 for the first element.
fruits = ("apple", "banana", "cherry")
print(fruits[0]) # Accessing the first element
print(fruits[1]) # Accessing the second element
banana
73. Python - Update Tuples
Tuples are immutable, meaning their items cannot be updated directly. However, you can convert them to a list and then modify the list.
fruits = ("apple", "banana", "cherry")
fruits_list = list(fruits) # Converting tuple to list
fruits_list[1] = "orange" # Updating list
fruits = tuple(fruits_list) # Converting list back to tuple
print(fruits)
74. Python - Unpack Tuples
Tuple unpacking allows you to assign individual elements of a tuple to variables.
fruits = ("apple", "banana", "cherry")
a, b, c = fruits # Unpacking tuple
print(a, b, c)
75. Python - Loop Tuples
Tuples can be looped through using a for loop to access each element.
fruits = ("apple", "banana", "cherry")
for fruit in fruits:
print(fruit)
banana
cherry
76. Python - Join Tuples
Tuples can be joined by concatenating them using the + operator.
tuple1 = ("apple", "banana")
tuple2 = ("cherry", "date")
joined_tuple = tuple1 + tuple2 # Using + operator to join
print(joined_tuple)
77. Python - Tuple Methods
Tuples provide a few built-in methods like count() and index() to perform operations on them.
fruits = ("apple", "banana", "cherry", "banana")
print(fruits.count("banana")) # Count occurrences of 'banana'
print(fruits.index("cherry")) # Find the index of 'cherry'
2
78. Python - Tuple Exercises
Tuple exercises help you practice and improve your understanding of tuple operations in Python.
fruits = ("apple", "banana", "cherry")
print(fruits[1]) # Access second element
print(fruits[-1]) # Access last element
print(fruits.count("banana")) # Count occurrences of 'banana'
cherry
1
79. Python Sets
Sets are unordered collections of unique elements.
fruits = {"apple", "banana", "cherry"}
print(fruits)
80. Python - Access Set Items
Set items cannot be accessed by index, but you can loop through the set to access each item.
fruits = {"apple", "banana", "cherry"}
for fruit in fruits:
print(fruit)
banana
cherry
81. Python - Add Set Items
You can add elements to a set using the add() method.
fruits = {"apple", "banana", "cherry"}
fruits.add("date") # Adding a new item
print(fruits)
82. Python - Remove Set Items
Set items can be removed using remove(), discard(), or pop().
fruits = {"apple", "banana", "cherry"}
fruits.remove("banana") # Removes 'banana' from the set
print(fruits)
83. Python - Loop Sets
Sets can be looped through using a for loop to access each element.
fruits = {"apple", "banana", "cherry"}
for fruit in fruits:
print(fruit)
banana
cherry
84. Python - Join Sets
Sets can be joined using the union() method or the | operator.
set1 = {"apple", "banana"}
set2 = {"cherry", "date"}
joined_set = set1 | set2 # Using | operator to join
print(joined_set)
85. Python - Copy Sets
Sets can be copied using the copy() method.
fruits = {"apple", "banana", "cherry"}
fruits_copy = fruits.copy() # Creating a copy of the set
print(fruits_copy)
86. Python - Set Operators
Sets support various operators like union (|), intersection (&), difference (-), and symmetric difference (^).
set1 = {"apple", "banana", "cherry"}
set2 = {"banana", "cherry", "date"}
union_set = set1 | set2 # Union
intersection_set = set1 & set2 # Intersection
difference_set = set1 - set2 # Difference
sym_diff_set = set1 ^ set2 # Symmetric difference
print(union_set)
print(intersection_set)
print(difference_set)
print(sym_diff_set)
{'banana', 'cherry'}
{'apple'}
{'apple', 'date'}
87. Python - Set Methods
Sets have various built-in methods like add(), remove(), pop(), and clear() to perform operations on sets.
fruits = {"apple", "banana", "cherry"}
fruits.add("date") # Adding an element
fruits.remove("banana") # Removing an element
fruits.pop() # Removing a random element
fruits.clear() # Removing all elements
print(fruits)
88. Python - Set Exercises
Set exercises help you practice and improve your understanding of set operations in Python.
fruits = {"apple", "banana", "cherry"}
fruits.add("date") # Adding an element
fruits.remove("banana") # Removing an element
print(fruits)
89. Python - Dictionaries
Dictionaries are unordered collections of key-value pairs.
person = {"name": "John", "age": 30, "city": "New York"}
print(person)
90. Python - Access Dictionary Items
Dictionary items can be accessed using their keys.
person = {"name": "John", "age": 30, "city": "New York"}
print(person["name"]) # Accessing by key
print(person.get("age")) # Using the get() method
30
91. Python - Change Dictionary Items
Dictionary values can be changed by assigning new values to existing keys.
person = {"name": "John", "age": 30, "city": "New York"}
person["age"] = 31 # Changing the value of 'age'
print(person)
92. Python - Add Dictionary Items
Items can be added to a dictionary by assigning a new key-value pair.
person = {"name": "John", "age": 30}
person["city"] = "New York" # Adding a new key-value pair
print(person)
93. Python - Remove Dictionary Items
Dictionary items can be removed using methods like del, pop(), or popitem().
person = {"name": "John", "age": 30, "city": "New York"}
person.pop("age") # Removing by key using pop()
del person["city"] # Removing by key using del
print(person)
94. Python - Dictionary View Objects
View objects provide a dynamic view of the dictionary's keys, values, and items.
person = {"name": "John", "age": 30, "city": "New York"}
keys_view = person.keys() # View of keys
values_view = person.values() # View of values
items_view = person.items() # View of items
print(keys_view)
print(values_view)
print(items_view)
dict_values(['John', 30, 'New York'])
dict_items([('name', 'John'), ('age', 30), ('city', 'New York')])
95. Python - Loop Dictionaries
Dictionaries can be looped through using for loops to access keys, values, or key-value pairs.
person = {"name": "John", "age": 30, "city": "New York"}
for key, value in person.items():
print(key, value)
age 30
city New York
96. Python - Copy Dictionaries
Dictionaries can be copied using the copy() method.
person = {"name": "John", "age": 30, "city": "New York"}
person_copy = person.copy() # Creating a copy of the dictionary
print(person_copy)
97. Python - Nested Dictionaries
Nested dictionaries are dictionaries inside dictionaries, useful for representing complex data structures.
person = {"name": "John", "details": {"age": 30, "city": "New York"}}
print(person["details"]["age"]) # Accessing nested dictionary value
98. Python - Dictionary Methods
Dictionaries have several methods like update(), get(), and pop() for manipulating key-value pairs.
person = {"name": "John", "age": 30, "city": "New York"}
person.update({"age": 31}) # Updating value of 'age'
print(person.get("city")) # Accessing value using get()
print(person)
{'name': 'John', 'age': 31, 'city': 'New York'}
99. Python - Dictionary Exercises
Dictionary exercises allow you to practice and improve your understanding of dictionaries in Python.
person = {"name": "John", "age": 30, "city": "New York"}
person["job"] = "Engineer" # Adding a new key-value pair
person["age"] = 31 # Updating the age
print(person)
100. Python Arrays
Arrays in Python can be created using the array module, but lists are more commonly used for storing elements.
import array
arr = array.array("i", [1, 2, 3, 4, 5]) # Creating an array of integers
print(arr)
101. Python - Access Array Items
Array items can be accessed using their index, similar to lists.
import array
arr = array.array("i", [1, 2, 3, 4, 5])
print(arr[2]) # Accessing the 3rd element (index 2)
102. Python - Add Array Items
Array items can be added using methods like append(), insert(), or extend().
import array
arr = array.array("i", [1, 2, 3, 4, 5])
arr.append(6) # Adding an item at the end
print(arr)
103. Python - Remove Array Items
Array items can be removed using methods like remove() or pop().
import array
arr = array.array("i", [1, 2, 3, 4, 5])
arr.remove(3) # Removing first occurrence of 3
print(arr)
104. Python - Loop Arrays
Arrays can be looped through using for loops to access each item.
import array
arr = array.array("i", [1, 2, 3, 4, 5])
for item in arr:
print(item)
2
3
4
5
105. Python - Copy Arrays
Arrays can be copied using the copy() method.
import array
arr = array.array("i", [1, 2, 3, 4, 5])
arr_copy = arr.copy() # Creating a copy of the array
print(arr_copy)
106. Python - Reverse Arrays
Arrays can be reversed using the reverse() method.
import array
arr = array.array("i", [1, 2, 3, 4, 5])
arr.reverse() # Reversing the array
print(arr)
107. Python - Sort Arrays
Arrays can be sorted using the sort() method.
import array
arr = array.array("i", [3, 1, 4, 5, 2])
arr.sort() # Sorting the array
print(arr)
108. Python - Join Arrays
Arrays can be joined together using the + operator.
import array
arr1 = array.array("i", [1, 2, 3])
arr2 = array.array("i", [4, 5, 6])
arr3 = arr1 + arr2 # Joining two arrays
print(arr3)
109. Python - Array Methods
Arrays have methods like append(), insert(), pop(), and more for manipulating items.
import array
arr = array.array("i", [1, 2, 3, 4, 5])
arr.append(6) # Adding item at the end
arr.insert(1, 7) # Inserting item at a specific position
print(arr)
110. Python - Array Exercises
Array exercises help you practice your understanding of array operations.
import array
arr = array.array("i", [10, 20, 30, 40, 50])
arr.append(60) # Adding item to array
arr.remove(30) # Removing item from array
print(arr)
111. Python - File Handling
File handling allows you to read, write, and manipulate files in Python.
file = open("example.txt", "w") # Open file in write mode
file.write("Hello, Python!") # Write to file
file.close() # Close the file
file = open("example.txt", "r") # Open file in read mode
content = file.read() # Read file content
print(content)
112. Python - Write to File
In Python, you can write to a file using the write()
method.
file = open("example.txt", "w") # Open file in write mode
file.write("This is a test.") # Write to file
file.close() # Close the file
113. Python - Read Files
To read a file in Python, you can use the read()
or readlines()
method.
file = open("example.txt", "r") # Open file in read mode
content = file.read() # Read content
print(content) file.close()
114. Python - Renaming and Deleting Files
You can rename or delete files using the os.rename()
and os.remove()
methods.
import os
os.rename("example.txt", "renamed_example.txt") # Renaming file
os.remove("renamed_example.txt") # Deleting file
115. Python - Directories
In Python, you can create, delete, and navigate directories using methods from the os
module.
import os
os.mkdir("my_directory") # Create a new directory
os.rmdir("my_directory") # Remove the directory
116. Python - File Methods
Python provides various methods to work with files, such as read()
, write()
, seek()
, and tell()
.
file = open("example.txt", "w") # Open file in write mode
file.write("Learning file handling.") # Write to file
file.seek(0) # Move file pointer to the beginning
content = file.read() # Read content
print(content) file.close()
117. Python - OS File/Directory Methods
The os
module provides several methods to manipulate files and directories, such as os.path.exists()
, os.makedirs()
, etc.
import os
print(os.path.exists("example.txt")) # Check if file exists
os.makedirs("new_directory") # Create a new directory
(No output, directory "new_directory" is created)
118. Python - OS Path Methods
Python’s os.path
module provides methods for manipulating file and directory paths, such as os.path.join()
, os.path.basename()
, etc.
import os
path = "example.txt"
print(os.path.basename(path)) # Extract base name
print(os.path.dirname(path)) # Extract directory name
(empty string, as no directory is specified)
119. Object Oriented Programming
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of objects, which contain data and methods.
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def display_info(self):
print(f"Brand: {self.brand}, Model: {self.model}")
my_car = Car("Toyota", "Corolla")
my_car.display_info() # Output: Brand: Toyota, Model: Corolla
120. Python - OOPs Concepts
Object-Oriented Programming (OOP) concepts include classes, objects, inheritance, polymorphism, encapsulation, and abstraction.
class Animal:
def sound(self):
print("Animal makes a sound")
class Dog(Animal):
def sound(self):
print("Dog barks")
dog = Dog()
dog.sound() # Output: Dog barks
121. Python - Classes & Objects
Classes define the structure of objects, and objects are instances of classes.
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
my_car = Car("Honda", "Civic")
print(my_car.brand, my_car.model) # Output: Honda Civic
122. Python - Class Attributes
Class attributes are variables that are shared among all instances of a class.
class Person:
age = 25 # Class attribute
p1 = Person()
p2 = Person()
print(p1.age) # Output: 25
print(p2.age) # Output: 25
25
123. Python - Class Methods
Class methods are methods that are bound to the class rather than instances.
class Calculator:
@classmethod
def add(cls, x, y):
return x + y
result = Calculator.add(5, 10)
print(result) # Output: 15
124. Python - Static Methods
Static methods do not require access to instance or class-level variables.
class Math:
@staticmethod
def multiply(x, y):
return x * y
result = Math.multiply(4, 5)
print(result) # Output: 20
125. Python - Constructors
Constructors are special methods used for initializing new objects in Python.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person1 = Person("Alice", 30)
print(person1.name, person1.age) # Output: Alice 30
126. Python - Access Modifiers
Access modifiers are used to control the access level of attributes and methods in Python classes.
class Person:
def __init__(self, name):
self.__name = name # Private attribute
p1 = Person("John")
print(p1.__name) # This will raise an error because __name is private
127. Python - Inheritance
Inheritance allows a class to inherit properties and methods from another class.
class Animal:
def sound(self):
print("Animal makes a sound")
class Dog(Animal):
def sound(self):
print("Dog barks")
dog = Dog()
dog.sound() # Output: Dog barks
128. Python - Polymorphism
Polymorphism allows methods to do different things based on the object it is acting upon.
class Dog:
def sound(self):
print("Bark")
class Cat:
def sound(self):
print("Meow")
def make_sound(animal):
animal.sound() # Calls appropriate sound based on the object
dog = Dog()
cat = Cat()
make_sound(dog) # Output: Bark
make_sound(cat) # Output: Meow
Meow
129. Python - Method Overriding
Method overriding allows a subclass to provide a specific implementation of a method already defined in its superclass.
class Animal:
def sound(self):
print("Animal makes a sound")
class Dog(Animal):
def sound(self):
print("Dog barks") # Overriding method
dog = Dog()
dog.sound() # Output: Dog barks
130. Python - Method Overloading
Python does not support method overloading like other languages, but you can achieve similar functionality using default arguments or variable-length arguments.
class Calculator:
def add(self, *args):
return sum(args)
calc = Calculator()
print(calc.add(1, 2)) # Output: 3
print(calc.add(1, 2, 3)) # Output: 6
6
131. Python - Dynamic Binding
In Python, method calls are resolved at runtime, which is known as dynamic binding.
class Person:
def greet(self):
print("Hello from Person")
class Employee(Person):
def greet(self):
print("Hello from Employee")
e = Employee()
e.greet() # Output: Hello from Employee
132. Python - Dynamic Typing
Python uses dynamic typing, which means variable types are assigned at runtime and do not need to be declared explicitly.
x = 5 # x is an integer
print(type(x)) # Output:
x = "Hello" # Now x is a string
print(type(x)) # Output:
133. Python - Abstraction
Abstraction allows hiding the complexity of a system and exposing only the essential features.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
c = Circle(5)
print(c.area()) # Output: 78.5
134. Python - Encapsulation
Encapsulation is the concept of bundling data and methods that operate on the data into a single unit or class.
class Employee:
def __init__(self, name, salary):
self.__name = name # Private attribute
self.__salary = salary # Private attribute
def get_salary(self):
return self.__salary
emp = Employee("John", 50000)
print(emp.get_salary()) # Output: 50000
135. Python - Interfaces
Python does not have interfaces like other languages, but abstract base classes (ABCs) can be used to define interfaces.
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
class Dog(Animal):
def sound(self):
print("Bark")
dog = Dog()
dog.sound() # Output: Bark
136. Python - Packages
Packages are a way of organizing related modules in Python.
# Directory structure:
# mypackage/
# __init__.py
# module1.py
#
# mypackage/module1.py
# def greet():
# print("Hello from module 1")
# Using the package:
import mypackage.module1
mypackage.module1.greet() # Output: Hello from module 1
137. Python - Inner Classes
Inner classes are defined within another class and can be used to encapsulate functionality.
class Outer:
class Inner:
def display(self):
print("Inside Inner class")
outer = Outer()
inner = outer.Inner()
inner.display() # Output: Inside Inner class
138. Python - Anonymous Class and Objects
Anonymous classes are those that do not have a name. They are used when an object is needed for temporary use.
obj = type("Anonymous", (object,), {"name": "John", "age": 30})()
print(obj.name, obj.age) # Output: John 30
139. Python - Singleton Class
A singleton class ensures that only one instance of the class is created.
class Singleton:
_instance = None
def __new__(cls):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(cls)
return cls._instance
obj1 = Singleton()
obj2 = Singleton()
print(obj1 is obj2) # Output: True
140. Python - Wrapper Classes
Wrapper classes are used to "wrap" primitive data types to provide additional functionality.
class Integer:
def __init__(self, value):
self.value = value
def add(self, other):
return self.value + other.value
int1 = Integer(10)
int2 = Integer(20)
result = int1.add(int2)
print(result) # Output: 30
141. Python - Enums
Enums are used to define a set of symbolic names bound to unique, constant integer values.
from enum import Enum
class Day(Enum):
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3
print(Day.MONDAY) # Output: Day.MONDAY
142. Python - Reflection
Reflection in Python allows a program to examine and modify its structure at runtime.
class Person:
def __init__(self, name):
self.name = name
p = Person("John")
print(dir(p)) # Lists all attributes and methods of the object
print(getattr(p, "name")) # Output: John
John
143. Python Errors & Exceptions
Errors in Python can be categorized into syntax errors and exceptions. Exceptions are errors that occur at runtime.
144. Python - Syntax Errors
Syntax errors occur when the Python interpreter encounters code that it cannot parse.
print("Hello World" # Missing closing parenthesis
145. Python - Exceptions
Exceptions in Python are runtime errors that can be handled using try-except blocks.
try:
num = 10 / 0
except ZeroDivisionError as e:
print("Error:", e) # Output: division by zero
146. Python - try-except Block
The try-except block is used to catch exceptions and handle errors without crashing the program.
try:
num = int(input("Enter a number: "))
except ValueError:
print("Invalid input, please enter a number.")
147. Python - try-finally Block
The finally block, if specified, is always executed after the try block, regardless of whether an exception occurred.
try:
file = open("test.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found")
finally:
file.close() # Ensures the file is closed
148. Python - Raising Exceptions
You can raise exceptions manually using the raise keyword.
def check_age(age):
if age < 18:
raise ValueError("Age must be 18 or older")
try:
check_age(15)
except ValueError as e:
print(e) # Output: Age must be 18 or older
149. Python - Exception Chaining
Exception chaining allows you to raise a new exception while preserving the original exception.
try:
1 / 0
except ZeroDivisionError as e:
raise ValueError("A custom error occurred") from e
raise from the original exception
150. Python Nested try Block
A nested try block means one try block inside another try block, with each try-except handling different exceptions.
try:
try:
num = int(input("Enter a number: "))
except ValueError:
print("Not a valid number")
except Exception as e:
print("An error occurred:", e)
151. Python - User-defined Exception
User-defined exceptions are created by inheriting the built-in Exception class and adding custom functionality.
class AgeTooSmallError(Exception):
pass
def check_age(age):
if age < 18:
raise AgeTooSmallError("Age must be 18 or older")
try:
check_age(15)
except AgeTooSmallError as e:
print(e) # Output: Age must be 18 or older
152. Python - Logging
Logging allows you to track events that happen while the program runs, which can help with debugging and tracking application behavior.
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug("This is a debug message")
logging.info("This is an info message")
INFO:root:This is an info message
153. Python - Assertions
Assertions are used to test if a condition is true during runtime. If the condition is false, an AssertionError is raised.
x = 10
assert x == 10, "x is not equal to 10"
assert x == 5, "x is not equal to 5" # This will raise an AssertionError
154. Python - Built-in Exceptions
Python provides several built-in exceptions that are used to handle specific errors, such as ZeroDivisionError, FileNotFoundError, and more.
try:
num = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
155. Python Multithreading
Multithreading is a technique that allows multiple threads to run concurrently within a program, improving efficiency in I/O-bound tasks.
156. Python - Multithreading
Multithreading is used to execute multiple threads simultaneously, each performing a different task in parallel.
import threading
def print_numbers():
for i in range(5):
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
1
2
3
4
157. Python - Thread Life Cycle
The life cycle of a thread consists of several stages: new, runnable, running, waiting, and terminated.
158. Python - Creating a Thread
To create a thread, you use the `threading.Thread()` method and provide the function to execute in the new thread.
import threading
def say_hello():
print("Hello from the thread!")
thread = threading.Thread(target=say_hello)
thread.start() # Start the thread
159. Python - Starting a Thread
To start a thread, call the `start()` method after creating a thread instance.
import threading
def print_hello():
print("Hello, Threading!")
thread = threading.Thread(target=print_hello)
thread.start() # Start the thread
160. Python Joining Threads
The `join()` method is used to block the main thread until the thread that calls `join()` finishes its execution.
import threading
def print_numbers():
for i in range(5):
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
thread.join() # Main thread waits for this thread to finish print("Thread has finished execution")
1
2
3
4
Thread has finished execution
161. Python - Naming Thread
Threads can be given specific names using the `name` argument when creating a thread, or by using the `setName()` method.
import threading
def thread_task():
print("This is the worker thread.")
thread = threading.Thread(target=thread_task, name="WorkerThread")
thread.start()
print("Thread name:", thread.name) # Output: WorkerThread
Thread name: WorkerThread
162. Python - Thread Scheduling
Thread scheduling refers to the process of allocating CPU time for threads to execute in a multithreading environment.
163. Python - Thread Pools
Thread pools are used to manage a group of threads that can be reused for executing multiple tasks concurrently.
164. Python - Main Thread
The main thread is the primary thread in which the Python program starts executing. All other threads are spawned from it.
165. Python - Thread Priority
Thread priority determines the order in which threads are executed when there are multiple threads in the system.
166. Python - Daemon Threads
Daemon threads are background threads that automatically terminate when the main program ends, without blocking the program's termination.
import threading
def background_task():
print("Background task running")
thread = threading.Thread(target=background_task)
thread.daemon = True # Set the thread as daemon
thread.start() # It will terminate when the main thread ends
167. Python - Synchronizing Threads
Thread synchronization ensures that shared resources are accessed by only one thread at a time to avoid data corruption.
import threading
lock = threading.Lock()
def synchronized_task():
with lock:
print("Thread-safe operation")
thread1 = threading.Thread(target=synchronized_task)
thread2 = threading.Thread(target=synchronized_task)
thread1.start()
thread2.start()
Thread-safe operation
168. Python Synchronization
Synchronization is a technique to ensure that multiple threads do not access shared resources simultaneously.
169. Python - Inter-thread Communication
Inter-thread communication allows threads to exchange data, often using mechanisms like events, queues, or condition variables.
import threading
import queue
def producer(q):
q.put("Data from producer")
def consumer(q):
data = q.get()
print(data)
q = queue.Queue()
thread1 = threading.Thread(target=producer, args=(q,))
thread2 = threading.Thread(target=consumer, args=(q,))
thread1.start()
thread2.start()
170. Python - Thread Deadlock
Deadlock occurs when two or more threads are blocked forever, each waiting on the other to release a resource.
171. Python Interrupting a Thread
A thread can be interrupted or terminated using the `Thread._stop()` method or by setting a flag in the thread.
import threading
import time
def thread_task():
for i in range(5):
print(i)
time.sleep(1)
thread = threading.Thread(target=thread_task)
thread.start()
time.sleep(2) # Wait for 2 seconds
thread._stop() # Interrupt the thread
print("Thread interrupted")
1
Thread interrupted
172. Python Networking
Networking in Python allows for communication between devices over a network using various protocols like TCP/IP.
173. Python Networking
Python provides modules such as `socket` and `socketserver` for implementing network communication protocols in your applications.
174. Python - Socket Programming
Socket programming allows for communication between computers over a network. It is used to create both server and client applications.
import socket
# Create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to a server
s.connect(("localhost", 8080))
s.sendall(b"Hello, Server")
response = s.recv(1024)
print(response.decode())
s.close()
175. Python Libraries
Python libraries are collections of pre-written code that you can use to perform common tasks, making your development process faster.
176. NumPy Tutorial
NumPy is a powerful library for numerical computing in Python. It provides support for large multidimensional arrays and matrices.
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr)
177. Pandas Tutorial
Pandas is a data manipulation and analysis library that provides data structures like DataFrames and Series to handle structured data.
import pandas as pd
data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]}
df = pd.DataFrame(data)
print(df)
0 Alice 25
1 Bob 30
178. SciPy Tutorial
SciPy is a library used for scientific and technical computing. It builds on NumPy and provides additional functionality like optimization, integration, and statistics.
179. Matplotlib Tutorial
Matplotlib is a plotting library that allows you to create static, animated, and interactive visualizations in Python.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)
plt.show()
180. Django Tutorial
Django is a high-level Python web framework that promotes rapid development and clean, pragmatic design for web applications.
181. OpenCV Tutorial
OpenCV is a library used for computer vision tasks, such as image and video processing, facial recognition, and more.
182. Python Miscellaneous
This section covers various miscellaneous Python topics that don't fall under any specific category but are important in Python development.
183. Python Date & Time
Python provides modules like `datetime` for handling and manipulating dates and times in programs.
import datetime
now = datetime.datetime.now()
print(now)
184. Python Maths
Python provides a `math` module to perform mathematical operations like trigonometric functions, logarithms, and more.
import math
result = math.sqrt(16)
print(result)
185. Python Iterators
Iterators allow you to traverse through all the elements in a collection, such as lists or tuples, one at a time.
my_list = [1, 2, 3, 4]
my_iter = iter(my_list)
print(next(my_iter)) # Output: 1
print(next(my_iter)) # Output: 2
2
186. Python - Generators
Generators are functions that allow you to iterate over a sequence of values, generating each value on the fly instead of storing the entire sequence in memory.
def my_generator():
yield 1
yield 2
yield 3
g = my_generator()
print(next(g)) # Output: 1
print(next(g)) # Output: 2
2
187. Python - Closures
A closure is a nested function that has access to variables from the outer function even after the outer function has finished execution.
def outer(x):
def inner(y):
return x + y
return inner
closure_func = outer(5)
print(closure_func(10)) # Output: 15
188. Python - Decorators
Decorators are a way to modify the behavior of a function or a method. They allow you to wrap another function to extend its behavior.
def my_decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
@my_decorator
def hello():
print("Hello, World!")
hello()
Hello, World!
After function call
189. Python - Recursion
Recursion occurs when a function calls itself in order to solve a problem by breaking it into smaller instances of the same problem.
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
190. Python - Reg Expressions
Regular expressions (RegEx) are used to match patterns in strings and extract information or perform replacements.
import re
pattern = r"\d+"
text = "There are 123 apples"
result = re.findall(pattern, text)
print(result) # Output: ['123']
191. Python - PIP
PIP is a package manager for Python, used to install and manage third-party libraries.
# pip install numpy
192. Python - Database Access
Python provides libraries like `sqlite3` for database access, allowing you to execute queries, insert data, and manage databases.
import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS users (name TEXT, age INTEGER)''')
conn.commit()
conn.close()
193. Python - Weak References
Weak references allow you to reference objects without increasing their reference count, enabling better memory management in some cases.
194. Python - Serialization
Serialization refers to the process of converting an object into a byte stream to store it in a file or send it over the network. The `pickle` module is commonly used for serialization in Python.
import pickle
data = {'name': 'Alice', 'age': 25}
with open('data.pkl', 'wb') as f:
pickle.dump(data, f)
195. Python - Templating
Templating is used to separate the presentation logic from business logic, commonly used in web frameworks like Flask and Django.
196. Python - Output Formatting
Python provides ways to format output, such as f-strings and the `format()` method.
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
197. Python - Performance Measurement
Performance measurement in Python can be done using the `time` and `timeit` modules to evaluate the efficiency of code.
198. Python - Data Compression
Python supports data compression with modules like `gzip`, `zipfile`, and `bz2`, allowing you to compress and decompress files.
import gzip
with gzip.open('example.gz', 'wb') as f:
f.write(b'Hello, World!')
with gzip.open('example.gz', 'rb') as f:
print(f.read()) # Output: b'Hello, World!'
199. Python - CGI Programming
Common Gateway Interface (CGI) is used for creating web applications. Python's `cgi` module helps to interact with web servers.
# This is typically run on a web server
import cgi
form = cgi.FieldStorage()
name = form.getvalue('name')
print("Content-type: text/html")
print("
Hello, {}!
".format(name))200. Python - XML Processing
Python provides libraries like `xml.etree.ElementTree` to parse and manipulate XML data.
import xml.etree.ElementTree as ET
tree = ET.ElementTree(ET.Element("root"))
root = tree.getroot()
ET.SubElement(root, "child", name="child1")
tree.write("output.xml") # Creates an XML file
201. Python - GUI Programming
Python provides libraries like Tkinter and PyQt for creating Graphical User Interface (GUI) applications.
import tkinter as tk
window = tk.Tk()
label = tk.Label(window, text="Hello, GUI!")
label.pack()
window.mainloop()
202. Python - Command-Line Arguments
Python's `sys` module allows you to pass command-line arguments to a script and handle them in your program.
import sys
print(f"Command-line argument: {sys.argv[1]}") # Running `python script.py arg`
203. Python - Docstrings
Docstrings are used to document code, and can be accessed using the `help()` function or `.__doc__` attribute.
def greet(name):
"""This function greets the person by name."""
print(f"Hello, {name}")
print(greet.__doc__) # Output: This function greets the person by name.
204. Python - JSON
Python's `json` module is used to parse JSON data into Python objects and serialize Python objects into JSON format.
import json
data = {'name': 'Alice', 'age': 25}
json_string = json.dumps(data)
print(json_string) # Output: '{"name": "Alice", "age": 25}'
parsed_data = json.loads(json_string)
print(parsed_data) # Output: {'name': 'Alice', 'age': 25}
{'name': 'Alice', 'age': 25}
205. Python - Sending Email
Python's `smtplib` module allows you to send emails via an SMTP server.
import smtplib
from email.mime.text import MIMEText
msg = MIMEText("Hello, this is a test email.")
msg['Subject'] = 'Test Email'
msg['From'] = 'your_email@example.com'
msg['To'] = 'recipient_email@example.com'
with smtplib.SMTP('smtp.example.com') as server:
server.sendmail(msg['From'], msg['To'], msg.as_string())
206. Python - Further Extensions
Python has a variety of additional extensions, such as libraries for data visualization, web development, and machine learning.
207. Python - Tools/Utilities
Python provides various tools and utilities for different purposes, including file handling, compression, and more.
208. Python GUIs
Python allows you to build graphical user interfaces (GUIs) using libraries like Tkinter, PyQt, or Kivy.
209. Python - Abstract Base Classes
Abstract Base Classes (ABCs) are used to define common methods and interfaces for subclasses. Python provides `abc` module to create ABCs.
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
class Dog(Animal):
def sound(self):
print("Woof!")
dog = Dog()
dog.sound() # Output: Woof!
210. Python - Custom Exceptions
Python allows you to define your own exceptions by subclassing the built-in `Exception` class.
class MyException(Exception):
def __init__(self, message):
self.message = message
try:
raise MyException("This is a custom exception!")
except MyException as e:
print(e) # Output: This is a custom exception!
211. Python - Higher Order Functions
Higher-order functions take other functions as arguments or return functions as results. Python supports this with functions like `map()`, `filter()`, and `reduce()`.
def multiply(x, y):
return x * y
def apply_function(func, x, y):
return func(x, y)
print(apply_function(multiply, 2, 3)) # Output: 6
212. Python - Object Internals
Understanding the internals of Python objects can help optimize memory and performance. This includes the Python memory model and reference counting.
213. Python - Memory Management
Python uses automatic memory management, which includes garbage collection to manage memory usage efficiently.
import sys
a = [1, 2, 3]
print(sys.getsizeof(a)) # Output: memory size of the list
214. Python - Metaclasses
Metaclasses are classes of classes. They define how classes behave in Python and can be used to modify the creation of classes.
class MyMeta(type):
def __new__(cls, name, bases, dct):
dct['class_type'] = 'Custom Class'
return super().__new__(cls, name, bases, dct)
class MyClass(metaclass=MyMeta):
pass
print(MyClass.class_type) # Output: Custom Class
215. Python - Metaprogramming with Metaclasses
Metaprogramming involves writing code that manipulates code. Metaclasses are a form of metaprogramming that modify class creation.
216. Python - Mocking and Stubbing
Mocking and stubbing are techniques used in unit testing to simulate parts of the system, allowing for isolated testing of components.
from unittest.mock import MagicMock
mock = MagicMock()
mock.some_method.return_value = "Mocked!"
print(mock.some_method()) # Output: Mocked!
217. Python - Type Hints
Type hints allow specifying the expected types of function arguments and return values, making the code more readable and maintainable.
def add_numbers(a: int, b: int) -> int:
return a + b
print(add_numbers(2, 3)) # Output: 5
218. Python - Automation Tutorial
Python can automate repetitive tasks like file handling, web scraping, and system administration tasks. Libraries like `os`, `shutil`, `requests`, and `selenium` are commonly used.
219. Python - Humanize Package
The `humanize` package in Python allows converting data into human-readable formats, such as converting bytes into a human-readable file size.
import humanize
print(humanize.naturalsize(1024)) # Output: 1.0 kB
220. Python - Context Managers
Context managers allow managing resources such as files and network connections. They ensure that resources are properly cleaned up after use.
with open('file.txt', 'w') as file:
file.write('Hello, World!')
# File is automatically closed after the block
221. Python - Coroutines
Coroutines are special types of functions that allow pausing and resuming their execution. They are mainly used for asynchronous programming.
import asyncio
async def greet():
print("Hello!")
asyncio.run(greet()) # Output: Hello!
222. Python - Descriptors
Descriptors are objects that manage the attributes of other objects. They define how attributes are accessed and modified.
class MyDescriptor:
def __get__(self, instance, owner):
return "Hello, from Descriptor!"
class MyClass:
attr = MyDescriptor()
obj = MyClass()
print(obj.attr) # Output: Hello, from Descriptor!
223. Python - Diagnosing and Fixing Memory Leaks
Memory leaks occur when objects are not properly garbage collected. Tools like `gc` and `objgraph` can help diagnose and fix memory leaks in Python.
224. Python - Immutable Data Structures
Immutable data structures, such as tuples and frozensets, cannot be modified once created. These structures help avoid unintentional changes to data.
my_tuple = (1, 2, 3)
try:
my_tuple[0] = 10 # This will raise a TypeError
except TypeError as e:
print(e) # Output: 'tuple' object does not support item assignment