Complete Python Course

1. Python Basics

Python is a high-level, interpreted programming language that emphasizes readability and simplicity, making it a popular choice for both beginners and professionals.

2. Python - Home

Python is widely used in various domains including web development, data science, machine learning, and automation.

3. Python - Overview

Python supports multiple programming paradigms such as procedural, object-oriented, and functional programming. Its simple syntax makes it ideal for new programmers.

4. Python - History

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.

5. Python - Features

6. Python vs C++

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.

7. Python - Hello World Program

To print "Hello, World!" in Python:


# Hello World Program
print("Hello, World!")
    

8. Python - Application Areas

9. Python - Interpreter

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.

10. Python - Environment Setup

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.

11. Python - Virtual Environment

A virtual environment helps to create isolated spaces for different projects, avoiding conflicts between dependencies.


# Create a virtual environment
python -m venv myenv
    

12. Python - Basic Syntax

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.")
    

13. Python - Variables

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
    

14. Python - Data Types

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
    

15. Python - Type Casting

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)
    

Output:

10.0

16. Python - Unicode System

Python supports Unicode, allowing characters from various languages to be used in strings. Example:


# Unicode Example
text = "Hello, World! 😀"
print(text)
    

Output:

Hello, World! 😀

17. Python - Literals

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
    

18. Python - Operators

Operators are used to perform operations on variables and values. Python supports various operators such as arithmetic, comparison, and logical operators.

19. Python - Arithmetic 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
    

Output:

15

5

50

2.0

20. Python - Comparison Operators

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
    

Output:

True

False

False

21. Python - Assignment Operators

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)
    

Output:

15

17

20

22. Python - Logical Operators

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
    

Output:

False

True

False

23. Python - Bitwise Operators

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
    

Output:

1

7

6

24. Python - Membership Operators

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
    

Output:

True

True

25. Python - Identity Operators

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
    

Output:

True

False

26. Python - Operator Precedence

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)
    

Output:

13

25

27. Python Comments

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)
    

Output:

5

28. Python - User Input

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.")
    

Output:

Enter your name: John

Enter your age: 25

Hello John, you are 25 years old.

29. Python Numbers

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)
    

Output:

10 3.14 (2+3j)

30. Python - Booleans

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
    

Output:

False

True

False

31. Python Control Statements

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")
    

Output:

x is greater than 3

32. Python - Control Flow

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")
    

Output:

x is greater than 5

33. Python - Decision Making

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.")
    

Output:

You are eligible to vote.

34. Python - If Statement

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")
    

Output:

x is greater than 5

35. Python - If Else

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")
    

Output:

x is not greater than 5

36. Python - Nested If

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")
    

Output:

x is between 5 and 15

37. Python - Match-Case Statement

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")
    

Output:

Start of the work week!

38. Python - Loops

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)
    

Output:

0

1

2

39. Python - For Loops

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)
    

Output:

4

5

6

40. Python - For-Else Loops

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.")
    

Output:

0

1

2

Loop finished without interruption.

41. Python - While Loops

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
    

Output:

0

1

2

42. Python - Break Statement

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)
    

Output:

0

1

2

43. Python - Continue Statement

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)
    

Output:

0

1

2

4

44. Python - Pass Statement

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)
    

Output:

0

1

2

3

4

45. Python - Nested Loops

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}")
    

Output:

i=0, j=0

i=0, j=1

i=0, j=2

i=1, j=0

i=1, j=1

i=1, j=2

46. Python Functions

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()
    

Output:

Hello, World!

47. Python - Default Arguments

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
    

Output:

Hello, Alice!

Hello, Guest!

48. Python - Keyword Arguments

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
    

Output:

Hello Bob, you are 25 years old.

49. Python - Keyword-Only Arguments

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
    

Output:

Hello Alice, you are 30 years old.

50. Python - Positional Arguments

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
    

Output:

Hello Charlie, you are 28 years old.

51. Python - Positional-Only Arguments

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
    

Output:

Hello David, you are 35 years old.

52. Python - Arbitrary Arguments

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")
    

Output:

Hello Alice!

Hello Bob!

Hello Charlie!

53. Python - Variables Scope

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
    

Output:

x = 10, y = 20

10

54. Python - Function Annotations

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))
    

Output:

Hello Eve, you are 22 years old.

55. Python - Modules

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
    

Output:

4.0

56. Python - Built-in Functions

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
    

Output:

13

57. Python - Strings

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)
    

Output:

Hello, World!

58. Python - Slicing Strings

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
    

Output:

Hello

Hello

World!

59. Python - Modify Strings

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)
    

Output:

Hello World!

60. Python - String Concatenation

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)
    

Output:

Hello Alice

61. Python - String Formatting

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)
    

Output:

Hello Alice, you are 25 years old.

Hello Alice, you are 25 years old.

62. Python - Escape Characters

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)
    

Output:

Hello
World!

She said, "Hello!"

63. Python - String Methods

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
    

Output:

HELLO, WORLD!

hello, world!

Hello, Python!

64. Python - String Exercises

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)
    

Output:

4

dlrow olleh ,olleh

65. Python - Lists

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)
    

Output:

['apple', 'banana', 'cherry']

66. Python - Access List Items

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
    

Output:

apple

cherry

67. Python - Change List Items

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)
    

Output:

['apple', 'orange', 'cherry']

68. Python - Add List Items

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)
    

Output:

['apple', 'grapes', 'banana', 'cherry', 'orange', 'pear', 'melon']

69. Python - Remove List Items

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)
    

Output:

[]

70. Python - Loop Lists

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)
    

Output:

apple

banana

cherry

71. Python - List Comprehension

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)
    

Output:

['APPLE', 'BANANA', 'CHERRY']

72. Python - Sort Lists

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)
    

Output:

['apple', 'banana', 'cherry']

['cherry', 'banana', 'apple']

73. Python - Copy Lists

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)
    

Output:

['apple', 'banana', 'cherry']

74. Python - Join Lists

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)
    

Output:

['apple', 'banana', 'carrot', 'tomato']

75. Python - List Methods

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)
    

Output:

['apple', 'grapes', 'cherry', 'orange']

76. Python - List Exercises

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)
    

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

[2, 4, 6, 8, 10]

77. Python - Tuples

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)
    

Output:

('apple', 'banana', 'cherry')

78. Python - Access Tuple Items

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
    

Output:

apple

cherry

79. Python - Update Tuples

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)
    

Output:

('apple', 'orange', 'cherry')

80. Python - Unpack Tuples

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)
    

Output:

apple

banana

cherry

81. Python - Loop Tuples

You can loop through a tuple using a `for` loop.


# Looping through Tuple
fruits = ("apple", "banana", "cherry")
for fruit in fruits:
    print(fruit)
    

Output:

apple

banana

cherry

82. Python - Join Tuples

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)
    

Output:

('apple', 'banana', 'cherry', 'orange')

83. Python - Tuple Methods

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)
    

Output:

Count of 'banana': 2

Index of 'apple': 0

84. Python - Tuple Exercises

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)
    

Output:

(1, 2, 3, 4, 5)

Index of 'banana': 1

85. Python - Sets

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)
    

Output:

{'apple', 'banana', 'cherry'}

86. Python - Access Set Items

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)
    

Output:

apple

banana

cherry

87. Python - Add Set Items

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)
    

Output:

{'apple', 'banana', 'cherry', 'orange'}

88. Python - Remove Set Items

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)
    

Output:

{'apple', 'cherry'}

89. Python - Loop Sets

You can loop through the set using a `for` loop.


# Looping through Set
fruits = {"apple", "banana", "cherry"}
for fruit in fruits:
    print(fruit)
    

Output:

apple

banana

cherry

90. Python - Join Sets

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)
    

Output:

{'banana', 'orange', 'cherry', 'apple'}

91. Python - Copy Sets

To copy a set, you can use the `copy()` method.


# Copying a Set
fruits = {"apple", "banana", "cherry"}
fruits_copy = fruits.copy()
print(fruits_copy)
    

Output:

{'banana', 'cherry', 'apple'}

92. Python - Set Operators

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)
    

Output:

Union: {'apple', 'banana', 'cherry', 'date'}

Intersection: {'banana', 'cherry'}

Difference: {'apple'}

Symmetric Difference: {'apple', 'date'}

93. Python - Set Methods

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)
    

Output:

set()

94. Python - Set Exercises

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)
    

Output:

Union: {1, 2, 3, 4, 5, 6}

Intersection: {3, 4}

{'apple', 'cherry'}

95. Python - Dictionaries

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)
    

Output:

{'name': 'John', 'age': 30, 'city': 'New York'}

96. Python - Access Dictionary Items

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
    

Output:

John

30

97. Python - Change Dictionary Items

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)
    

Output:

{'name': 'John', 'age': 31, 'city': 'New York'}

98. Python - Add Dictionary Items

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)
    

Output:

{'name': 'John', 'age': 30, 'city': 'New York', 'email': 'john@example.com'}

99. Python - Remove Dictionary Items

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)
    

Output:

{'name': 'John'}

100. Python - Dictionary View Objects

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
    

Output:

dict_keys(['name', 'age', 'city'])

dict_values(['John', 30, 'New York'])

dict_items([('name', 'John'), ('age', 30), ('city', 'New York')])

101. Python - Loop Dictionaries

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)
    

Output:

name

age

city

John

30

New York

name John

age 30

city New York

102. Python - Copy Dictionaries

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)
    

Output:

{'name': 'John', 'age': 30, 'city': 'New York'}

103. Python - Nested Dictionaries

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
    

Output:

30

104. Python - Dictionary Methods

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)
    

Output:

{}

105. Python - Dictionary Exercises

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)
    

Output:

{'name': 'John', 'age': 31, 'city': 'New York', 'email': 'john@example.com'}

{'name': 'John', 'city': 'New York'}

106. Python - Arrays

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)
    

Output:

array('i', [1, 2, 3, 4, 5])

107. Python - Access Array Items

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
    

Output:

1

4

108. Python - Add Array Items

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)
    

Output:

array('i', [1, 2, 5, 3, 4])

109. Python - Remove Array Items

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)
    

Output:

array('i', [1, 2, 4, 5])

110. Python - Loop Arrays

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
    

Output:

1

2

3

4

5

111. Python - Copy Arrays

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)
    

Output:

array('i', [1, 2, 3])

112. Python - Reverse Arrays

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)
    

Output:

array('i', [5, 4, 3, 2, 1])

113. Python - Sort Arrays

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)
    

Output:

array('i', [1, 2, 3, 4, 5])

114. Python - Join Arrays

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)
    

Output:

array('i', [1, 2, 3, 4, 5, 6])

115. Python - Array Methods

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)
    

Output:

array('i', [1, 2, 6, 4, 5])

116. Python - Array Exercises

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)
    

Output:

array('i', [1, 3, 4, 5])

array('i', [1, 2, 3, 4, 5])

117. Python - File Handling

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.

118. Python - Write to File

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()
    

Output:

A new file `example.txt` is created, and the text "Hello, world!" is written inside it.

119. Python - Read Files

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()
    

Output:

Hello, world!

120. Python - Renaming and Deleting Files

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')
    

Output:

The file `example.txt` is renamed to `new_example.txt`, and then it is deleted.

121. Python - Directories

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')
    

Output:

A new directory `new_directory` is created and then removed.

122. Python - File Methods

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()
    

Output:

Hello, Python!

123. Python - OS File/Directory Methods

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)
    

Output:

True

['example.txt', 'other_file.txt']

124. Python - OS Path Methods

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)
    

Output:

folder/file.txt

/home/user/example.txt

example.txt

125. Python - OOPs Concepts

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.

126. Python - Classes & Objects

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()
    

Output:

Hello, my name is Alice and I am 30 years old.

127. Python - Class Attributes

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)
    

Output:

4

4

128. Python - Class Methods

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()
    

Output:

Hello, class method!

129. Python - Static Methods

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()
    

Output:

Hello, static method!

130. Python - Constructors

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)
    

Output:

John

25

131. Python - Access Modifiers

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())
    

Output:

Alice

30

132. Python - Inheritance

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
    

Output:

Animal is speaking

Dog is barking

133. Python - Polymorphism

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()
    

Output:

Animal is speaking

Dog is barking

134. Python - Method Overriding

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
    

Output:

Animal speaks

Dog barks

135. Python - Method Overloading

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")
    

Output:

Hello, World

Hello, Alice

136. Python - Dynamic Binding

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()
    

Output:

Dog barks

137. Python - Dynamic Typing

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))
    

Output:

<class 'int'>

<class 'str'>

138. Python - Abstraction

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()
    

Output:

Dog barks

139. Python - Encapsulation

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())
    

Output:

1500

140. Python - Interfaces

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())
    

Output:

78.5

141. Python - Packages

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))
    

Output:

4.0

142. Python - Inner Classes

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()
    

Output:

Hello from inner class

143. Python - Anonymous Class and Objects

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)
    

Output:

Alice

30

144. Python - Singleton Class

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)
    

Output:

True

145. Python - Wrapper Classes

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))
    

Output:

<class 'int'>

146. Python - Enums

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)
    

Output:

Color.RED

Color.GREEN

147. Python - Reflection

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"))
    

Output:

Alice

Bob

148. Python Errors & Exceptions

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.

149. Python - Syntax Errors

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")
    

Output:

SyntaxError: invalid syntax

150. Python - Exceptions

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.

151. Python - 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")
    

Output:

Cannot divide by zero

152. Python - try-finally Block

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")
    

Output:

This will always be executed

ZeroDivisionError: division by zero

153. Python - Raising Exceptions

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")
    

Output:

ValueError: Negative values are not allowed

154. Python - Exception Chaining

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
    

Output:

RuntimeError: Failed to open file

Caused by: FileNotFoundError: No such file or directory

155. Python - Nested try Block

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")
    

Output:

Caught inner division error

156. Python - User-defined Exception

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)
    

Output:

Value cannot be negative

157. Python - Logging

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")
    

Output:

ERROR:root:This is an error message

158. Python - Assertions

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
    

Output:

AssertionError: x should be less than 5

159. Python - Built-in Exceptions

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`.

160. Python - Multithreading

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.

161. Python - Thread Life Cycle

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
    

Output:

Thread started

Thread finished

162. Python - Creating a Thread

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
    

Output:

Hello from thread!

163. Python - Starting a 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
    

Output:

0

1

2

3

4

164. Python - Joining Threads

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")
    

Output:

Thread is running

Thread finished

Main thread ends

165. Python - Naming Thread

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}")
    

Output:

Thread is running

Thread Name: CustomThreadName

166. Python - Thread Scheduling

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.

167. Python - Thread Pools

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)
    

Output:

Task 0 is running

Task 1 is running

Task 2 is running

Task 3 is running

Task 4 is running

168. Python - Main Thread

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
    

Output:

Worker thread

169. Python - Thread Priority

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.

170. Python - Daemon 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
    

Output:

Daemon thread running

Daemon thread running

Daemon thread running

171. Python - Synchronizing Threads

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()
    

Output:

Thread is in the critical section

Thread is in the critical section

172. Python - Synchronization

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()
    

Output:

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

173. Python - Inter-thread Communication

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()
    

Output:

Produced: 0

Consumed: 0

Produced: 1

Consumed: 1

Produced: 2

Consumed: 2

Produced: 3

Consumed: 3

Produced: 4

Consumed: 4

174. Python - Thread Deadlock

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
    

Output (Deadlock Scenario):

Task 1 acquired lock1

Task 2 acquired lock2

175. Python - Interrupting a Thread

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
    

Output:

Thread is running

Thread is running

Thread is running

Thread interrupted and stopped

176. Python - Networking

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
    

Output (Server Side):

Server is listening...

Connection from ('127.0.0.1', 12346)

Output (Client Side):

Received from server: Hello from server

177. Python - Socket Programming

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
    

Output (Server Side):

Server waiting for connection...

Connection established with ('127.0.0.1', 12345)

Received: Hello, Server!

Output (Client Side):

Received from server: Hello, Server!

178. Python - URL Processing

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}")
    

Output:

Scheme: http

Netloc: www.example.com:8080

Path: /path

Params:

Query: query=python

Fragment: fragment

179. Python - Generics

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
    

Output:

123

Hello

180. Python Libraries

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.

181. NumPy Tutorial

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)
    

Output:

Array: [1 2 3 4 5]

Squared Array: [ 1 4 9 16 25]

Sum of Array: 15

182. Pandas Tutorial

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)
    

Output:

              Name  Age
            0    Alice   24
            1      Bob   27
            2  Charlie   22
            

Mean Age: 24.33

183. SciPy Tutorial

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)
    

Output:

Minimum of function: 5.0

184. Matplotlib Tutorial

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()
    

Output:

The code will generate a plot of the equation y = x^2, with the X and Y axes labeled accordingly.

185. Django Tutorial

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!")
    

Output:

The Django view will return "Hello, World!" when accessed through a browser.

186. OpenCV Tutorial

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()
    

Output:

The code will open an image file ('image.jpg') and display it in a window.

187. Python Miscellaneous

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.

188. Python - Date & Time

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)
    

Output:

Current Date and Time: 2024-11-22 14:30:15.675423

189. Python - Maths

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)
    

Output:

Square Root: 4.0

Factorial: 120

190. Python - Iterators

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))
    

Output:

1

2

191. Python - Generators

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)
    

Output:

1

2

3

4

5

192. Python - Closures

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)
    

Output:

15

193. Python - Decorators

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()
    

Output:

Before function call

Hello, World!

After function call

194. Python - Recursion

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))
    

Output:

120

195. Python - Reg Expressions

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)
    

Output:

['10']

196. Python - PIP

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
    

197. Python - Database Access

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()
    

198. Python - Weak References

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())
    

199. Python - Serialization

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)
    

200. Python - Templating

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)
    

201. Python - Output Formatting

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}")
    

202. Python - Performance Measurement

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")
    

203. Python - Data Compression

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)
    

204. Python - CGI Programming

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}

")

205. Python - XML Processing

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 = "Alice25"
root = ET.fromstring(data)
name = root.find("name").text
print(name)
    

206. Python - GUI Programming

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()
    

207. Python - Command-Line Arguments

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:])
    

208. Python - Docstrings

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__)
    

209. Python - JSON

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)
    

210. Python - Sending Email

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()
    

211. Python - Further Extensions

Python offers many further extensions that you can use for specific tasks, such as image processing, machine learning, and more.

212. Python - Tools/Utilities

Python provides several built-in tools for various utilities like debugging, profiling, and more.

213. Python - GUIs

Graphical User Interfaces (GUIs) can be created in Python using libraries like Tkinter and PyQt to create desktop applications.

213. Python - Abstract Base Classes

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!"
    

Output:


Method implemented!
    

214. Python - Custom Exceptions

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)
    

Output:


Something went wrong!
    

215. Python - Higher Order Functions

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
    

Output:


10
    

216. Python - Object Internals

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}
    

Output:


{'x': 10}
    

217. Python - Memory Management

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()
    

218. Python - Metaclasses

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
    

Output:


Creating class MyClass
    

219. Python - Metaprogramming with Metaclasses

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
    

Output:


Added dynamically
    

220. Python - Mocking and Stubbing

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
    

Output:


mocked value
    

221. Python - Monkey Patching

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
    

Output:


42
    

222. Python - Signal Handling

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)
    

223. Python - Type Hints

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
    

Output:


15
    

224. Python - Automation Tutorial

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')
    

225. Python - Humanize Package

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
    

Output:


1.0 kB
    

226. Python - Context Managers

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")
    

Output:


Entering the context
Inside the context
Exiting the context
    

227. Python - Coroutines

Coroutines are special types of functions that allow pausing

231. Python - Questions & Answers

Get commonly asked Python questions and answers, ranging from basic to advanced levels, covering various Python topics like syntax, libraries, and concepts.

232. Python - Online Quiz

Test your Python knowledge with an online quiz covering essential Python concepts like data structures, algorithms, and functions.

233. Python - Quick Guide

A quick guide to Python programming that covers the basics, syntax, and important topics in a concise format for beginners.

234. Python - Reference

The Python Reference provides detailed explanations of Python's syntax, libraries, and built-in functions to help developers understand how each feature works.

235. Python - Cheatsheet

A handy Python cheatsheet that summarizes key Python commands, functions, and syntax to help you quickly look up information while coding.

236. Python - Projects

Python project ideas for beginners and advanced learners, including real-world applications like web development, data science, automation, and more.

237. Python - Useful Resources

Find useful Python resources, including tutorials, documentation, books, and community forums to enhance your learning experience.

238. Python - Discussion

Join Python discussion forums to connect with other learners, ask questions, share knowledge, and get insights from experienced developers.

239. Python Compiler

An online Python compiler allows you to write, compile, and run Python code in your browser without needing to install any software.

240. NumPy Compiler

The NumPy compiler is an online tool for writing and executing Python code that uses the NumPy library for numerical computations and array manipulations.

241. Matplotlib Compiler

The Matplotlib compiler allows you to create and run Python code that generates visualizations like plots and graphs using the Matplotlib library.

242. SciPy Compiler

The SciPy compiler is an online platform for executing Python code that leverages the SciPy library for scientific and technical computing tasks.

243. UPSC IAS Exams Notes

Comprehensive notes for the UPSC IAS exams, covering various subjects like history, geography, politics, and current affairs to help candidates in their exam preparation.

244. Developer's Best Practices

A collection of coding and software development best practices to ensure code quality, maintainability, and efficiency for developers.

245. Questions and Answers

A set of frequently asked questions and their answers across various domains, including programming, general knowledge, and technical subjects.

246. Effective Resume Writing

Guidelines and tips for writing an effective resume that stands out to potential employers, with examples and templates for different fields.

247. HR Interview Questions

Common HR interview questions with sample answers to help candidates prepare for job interviews and understand what interviewers look for.

248. Computer Glossary

A glossary of computer-related terms and definitions, helping both beginners and advanced users to better understand technical jargon.

249. Who is Who

A guide to important personalities and their roles in various fields such as politics, science, literature, and more.