Python is a high-level, interpreted programming language that was created by Guido van Rossum and first released in 1991. It is known for its easy-to-read syntax, simplicity, and readability. Python supports multiple programming paradigms, including procedural, object-oriented, and functional programming. It has a large standard library, making it versatile and easy to use for tasks ranging from web development to machine learning, data analysis, automation, and more.
To print something in Python, we use the built-in print()
function. It allows you to display data, including strings, variables, and calculations. Here’s an example:
print("Hello, World!") # Output: Hello, World!
print(5 + 3) # Output: 8
The print()
function can also be used to print multiple values, separated by commas.
Python provides several built-in data types for different purposes. Here are the most common ones:
int
: Integer values (e.g., 1, -5, 42).float
: Decimal numbers (e.g., 3.14, -2.5).str
: Strings (e.g., "hello", "Python").list
: Ordered, mutable collections of items (e.g., [1, 2, 3, 4]).tuple
: Ordered, immutable collections of items (e.g., (1, 2, 3)).set
: Unordered collections of unique items (e.g., {1, 2, 3}).dict
: Unordered collection of key-value pairs (e.g., {"name": "Alice", "age": 25}).bool
: Boolean values (True
or False
).None
: A special type used to represent the absence of a value.The primary difference between lists and tuples in Python is that lists are mutable (they can be modified after creation), while tuples are immutable (once created, they cannot be changed). This makes tuples more efficient in terms of memory usage and performance. Lists are typically used when you need a collection of items that can be modified, whereas tuples are often used for fixed collections of items.
my_list = [1, 2, 3] # List
my_tuple = (1, 2, 3) # Tuple
A dictionary in Python is an unordered collection of key-value pairs. Each key is unique, and each key is associated with a value. Dictionaries are defined using curly braces {}
with key-value pairs separated by colons (:
). Example:
my_dict = {"name": "Alice", "age": 25}
print(my_dict["name"]) # Output: Alice
You can also use various methods like keys()
, values()
, and items()
to interact with dictionaries.
Functions in Python are defined using the def
keyword. A function can accept arguments, perform operations, and return a result. Functions help to organize code and avoid redundancy.
def greet(name):
return f"Hello, {name}!"
print(greet("Alice")) # Output: Hello, Alice!
Functions can return values using the return
statement, and if no return statement is provided, None
is returned by default.
Comments in Python are lines that are ignored by the interpreter and are used to add notes to the code. They help to explain the code, making it more readable and easier to understand.
#
).'''
or """
). Example:
# This is a single-line comment
print("Hello, World!") # This prints a message
'''
This is a
multi-line comment
explaining the code
'''
A variable in Python is a symbolic name that refers to a value stored in memory. Python is dynamically typed, which means you don't need to declare the type of a variable before using it. A variable can store various types of data like numbers, strings, lists, etc. You can assign values to variables using the =
operator.
x = 10 # Integer
name = "John" # String
Type casting is the process of converting one data type to another. In Python, this is done explicitly using built-in functions like int()
, float()
, str()
, etc. For example, you can convert a float to an integer or an integer to a string.
x = int(3.14) # Converts float to integer, result: 3
y = str(10) # Converts integer to string, result: '10'
==
checks for value equality. It returns True
if the values of the two objects are the same.is
checks for identity. It returns True
if both variables refer to the same object in memory (i.e., they are the exact same object). Example:
x = [1, 2, 3]
y = [1, 2, 3]
z = x
print(x == y) # True (values are the same)
print(x is y) # False (they are different objects in memory)
print(x is z) # True (both refer to the same object)
Conditional statements in Python allow you to make decisions based on whether a condition is True
or False
. The basic structure uses if
, elif
, and else
to execute different blocks of code.
age = 20
if age >= 18:
print("Adult")
else:
print("Minor")
The for
loop is used to iterate over a sequence (like a list, tuple, or range) and execute a block of code multiple times. Python's for
loop works by iterating directly over the elements of a sequence.
for i in range(5):
print(i)
The loop will iterate from 0
to 4
(the range is exclusive of the upper limit).
The while
loop repeats a block of code as long as the given condition is True
. The condition is evaluated before every iteration, so if it’s False
initially, the loop may never execute.
count = 0
while count < 5:
print(count)
count += 1
The break
statement is used to exit a loop prematurely. It can be used in both for
and while
loops to terminate the loop before the condition becomes False
.
for i in range(10):
if i == 5:
break
print(i) # Output: 0 1 2 3 4
The continue
statement is used to skip the current iteration of a loop and move to the next iteration. It is useful when you want to skip certain elements based on a condition but still continue looping.
for i in range(5):
if i == 3:
continue
print(i) # Output: 0 1 2 4
The pass
statement is a null operation used as a placeholder where syntactically required but no action is needed. It is often used in functions, loops, or conditionals that are yet to be implemented.
def my_function():
pass # Function does nothing yet
List comprehension provides a concise way to create lists by applying an expression to each item in an iterable, optionally filtering the items.
squares = [x**2 for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]
A list in Python can be created using square brackets []
with elements separated by commas. Lists are mutable and can contain mixed data types.
my_list = [1, 2, 3, 4, 5]
print(my_list) # Output: [1, 2, 3, 4, 5]
Elements in a list can be accessed using indices. The index starts from 0 for the first element.
my_list = [10, 20, 30]
print(my_list[1]) # Output: 20
A set in Python is an unordered collection of unique elements. Sets do not allow duplicate values and are defined using curly braces {}
. They are mutable and are commonly used for membership tests and removing duplicates from a list.
my_set = {1, 2, 3, 4}
print(my_set) # Output: {1, 2, 3, 4}
my_set.add(5) # Adds element 5 to the set
list
is an ordered collection of items, where duplicates are allowed, and the items are indexed.set
is an unordered collection of unique elements, with no indexing and no duplicate elements. Sets are typically used when you need to store unique values without worrying about order. Example:
list_example = [1, 2, 2, 3]
set_example = {1, 2, 2, 3}
print(list_example) # Output: [1, 2, 2, 3]
print(set_example) # Output: {1, 2, 3}
Python provides a mechanism for handling errors and exceptions using try
, except
, and optionally finally
. This allows you to catch specific errors, handle them appropriately, and clean up resources if necessary.
try:
x = 10 / 0
except ZeroDivisionError as e:
print("Error:", e) # Output: Error: division by zero
finally:
print("Execution complete.") # Always executes
The else
block in a try-except
structure is executed if no exception is raised in the try
block. It is commonly used for code that should run only when no errors occur.
try:
x = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Division successful.") # Output: Division successful.
The finally
block is always executed, regardless of whether an exception occurred or not. It is typically used for cleanup actions, like closing files or releasing resources.
try:
f = open("file.txt", "r")
except IOError:
print("File not found")
finally:
f.close() # Always executed to close the file, even if an error occurs
A lambda function is a small anonymous function defined using the lambda
keyword. It can have any number of arguments but only one expression. Lambda functions are often used for short, throwaway functions that are not meant to be reused.
add = lambda x, y: x + y
print(add(2, 3)) # Output: 5
Lambda functions provide a concise way to write small functions without the need to define a full function using def
. They are commonly used when passing a simple function as an argument to higher-order functions like map()
, filter()
, and sorted()
. Example with map()
:
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # Output: [1, 4, 9, 16]
A generator is a special type of iterable that generates values one at a time using the yield
keyword. It allows you to iterate over data without storing the entire dataset in memory, which is memory efficient, especially with large data.
def count_up_to(n):
count = 1
while count <= n:
yield count
count += 1
counter = count_up_to(5)
for num in counter:
print(num) # Output: 1 2 3 4 5
The yield
keyword is used in functions to create generators. It allows the function to return an intermediate result and pause its execution, resuming from the last yield
when called again. This allows for memory-efficient iteration over large datasets.
def my_generator():
yield 1
yield 2
yield 3
for value in my_generator():
print(value) # Output: 1 2 3
A module is a file containing Python code that can define functions, classes, and variables. A package is a collection of modules grouped together in a directory hierarchy. Python allows you to import these modules and packages into your code to reuse functionality.
import math
print(math.sqrt(16)) # Output: 4.0
from mypackage import mymodule
You can import a module in Python using the import
statement. There are different ways to import modules:
import math
print(math.pi)
from math import sqrt
print(sqrt(16)) # Output: 4.0
import numpy as np
The __init__
method is a special method in Python classes that is called when an object is instantiated. It is the constructor method, used to initialize the object’s attributes.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("Alice", 30)
print(person.name) # Output: Alice
Inheritance is a fundamental concept in object-oriented programming where one class (child class) inherits attributes and methods from another class (parent class). It allows for code reusability and is implemented using parentheses when defining the child class.
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def speak(self):
print("Dog barks")
dog = Dog()
dog.speak() # Output: Dog barks
Polymorphism allows objects of different classes to be treated as instances of the same class. It enables the same method name to work differently depending on the class that it is acting upon. In Python, polymorphism is achieved through method overriding and dynamic method calls.
class Cat:
def speak(self):
print("Meow")
class Dog:
def speak(self):
print("Woof")
animals = [Cat(), Dog()]
for animal in animals:
animal.speak() # Output: Meow Woof
Encapsulation is the concept of bundling data and methods that operate on that data within a single unit (class) and restricting access to some of the object's components. This is achieved using private and public attributes and methods. In Python, this is done using underscores: one underscore _
for protected members and two underscores __
for private members.
class Car:
def __init__(self, model):
self.model = model # public attribute
self.__speed = 0 # private attribute
def start_engine(self):
print(f"{self.model} engine started.")
def get_speed(self):
return self.__speed # private attribute access
my_car = Car("Toyota")
my_car.start_engine()
print(my_car.get_speed()) # Accessing private method
Abstraction is a concept that hides the complexity and shows only the essential features of an object. It is implemented using abstract classes in Python, which cannot be instantiated directly. The abc
module in Python is used to create abstract classes and methods.
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
A class in Python is a blueprint for creating objects (instances). It defines a set of attributes and methods that the objects created from the class will have. Classes are fundamental in object-oriented programming (OOP), allowing for encapsulation, inheritance, and polymorphism.
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def start(self):
print(f"The {self.brand} {self.model} is starting.")
car = Car("Toyota", "Corolla")
car.start() # Output: The Toyota Corolla is starting.
Object-Oriented Programming (OOP) in Python is a programming paradigm that uses objects and classes to organize code. OOP principles include:
Slicing allows you to extract a portion of a list, string, or tuple by specifying a start index, end index, and an optional step. The syntax is [start:end:step]
.
my_list = [10, 20, 30, 40, 50]
print(my_list[1:4]) # Output: [20, 30, 40]
The self
keyword in Python is used to refer to the instance of the class. It allows access to the instance's attributes and methods within the class. Every method in a class requires self
as its first parameter to reference the object it is being called on.
class Dog:
def __init__(self, name):
self.name = name # `self` refers to the instance
def bark(self):
print(f"{self.name} says Woof!")
dog = Dog("Buddy")
dog.bark() # Output: Buddy says Woof!
A method in Python is a function that is defined within a class and is associated with an object of that class. Methods typically operate on the instance (using self
) and can modify its state or perform actions.
class Person:
def greet(self):
print("Hello!")
person = Person()
person.greet() # Output: Hello!
class Car:
def __init__(self, model):
self.model = model
car1 = Car("Tesla")
car2 = Car("BMW")
You create an object by calling the class as if it were a function, passing any required arguments to the __init__
method (the constructor). The constructor initializes the object's attributes.
class Dog:
def __init__(self, name):
self.name = name
my_dog = Dog("Rex") # Creates an object of the Dog class
print(my_dog.name) # Output: Rex
__str__
: It is used to define a human-readable string representation of an object, typically for printing or displaying to users. It should return a string that is easy to understand.__repr__
: It is used to define a formal string representation of an object, aimed at developers. The goal is to return a string that can be used to recreate the object (if possible). Example:
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def __str__(self):
return f"Car: {self.brand} {self.model}"
def __repr__(self):
return f"Car('{self.brand}', '{self.model}')"
car = Car("Toyota", "Camry")
print(str(car)) # Output: Car: Toyota Camry
print(repr(car)) # Output: Car('Toyota', 'Camry')
@classmethod
decorator, these methods take the class (cls
) as the first parameter and can modify the class state. They are often used for factory methods.@staticmethod
decorator, static methods don't take self
or cls
as the first parameter. They are used when a method doesn't need to access the instance or class state. Example:
class MyClass:
@classmethod
def class_method(cls):
print("This is a class method")
@staticmethod
def static_method():
print("This is a static method")
MyClass.class_method() # Output: This is a class method
MyClass.static_method() # Output: This is a static method
The super()
function is used to call a method from the parent class in a derived class. It is commonly used in the __init__
method to initialize the parent class's attributes or to call overridden methods.
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # Calls the parent class's __init__ method
self.breed = breed
dog = Dog("Buddy", "Golden Retriever")
print(dog.name) # Output: Buddy
A decorator in Python is a function that modifies the behavior of another function or method. Decorators are used to extend or alter the behavior of the functions or methods without modifying the actual code. Decorators are often used for logging, authentication, and memoization. They are applied using the @decorator_name
syntax. Example:
def decorator_function(func):
def wrapper():
print("Before function execution")
func()
print("After function execution")
return wrapper
@decorator_function
def say_hello():
print("Hello!")
say_hello() # Output: Before function execution
# Hello!
# After function execution
An iterator in Python is an object that implements the __iter__()
and __next__()
methods, enabling you to iterate over a collection of items. Iterators allow you to loop through a sequence (like a list or string) without using indexing. Example:
my_list = [1, 2, 3]
my_iterator = iter(my_list)
print(next(my_iterator)) # Output: 1
print(next(my_iterator)) # Output: 2
When you use a for
loop with an iterable object, Python automatically calls the __iter__()
method on the object to get an iterator and then uses the __next__()
method to access the elements. This process continues until the iterator raises a StopIteration
exception. Example:
my_list = [1, 2, 3]
for item in my_list:
print(item)
# Output: 1
# Output: 2
# Output: 3
Python provides many built-in functions to perform common tasks. Some of the most commonly used built-in functions include:
print()
: Outputs data to the console.len()
: Returns the length of an object (e.g., list, string).max()
, min()
: Returns the largest and smallest item from a collection.sum()
: Returns the sum of elements in an iterable.range()
: Generates a sequence of numbers.abs()
: Returns the absolute value of a number.sorted()
: Returns a sorted list.type()
: Returns the type of an object. Example:
nums = [1, 2, 3, 4]
print(sum(nums)) # Output: 10
print(sorted(nums)) # Output: [1, 2, 3, 4]
The map()
function in Python is used to apply a function to all items in an iterable (like a list or tuple). It returns a map object, which is an iterator, and you can convert it to a list using list()
. Example:
numbers = [1, 2, 3]
squares = map(lambda x: x ** 2, numbers)
print(list(squares)) # Output: [1, 4, 9]
The filter()
function in Python is used to filter elements from an iterable based on a given function that returns a boolean value (True
or False
). Only the elements for which the function returns True
are included in the result. The filter()
function returns an iterator, which can be converted to a list using list()
. Example:
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers)) # Output: [2, 4, 6]
The reduce()
function from the functools
module in Python is used to apply a binary function (a function that takes two arguments) cumulatively to the items of an iterable. It reduces the iterable to a single value. Example:
from functools import reduce
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product) # Output: 24
copy()
: Creates a shallow copy of an object. For compound objects (like lists of lists), it copies only the references to the nested objects, not the nested objects themselves.deepcopy()
: Creates a deep copy of an object, meaning it copies not just the object, but also all the objects contained within it (recursively). Example:
import copy
lst = [[1, 2], [3, 4]]
shallow_copy = copy.copy(lst)
deep_copy = copy.deepcopy(lst)
lst[0][0] = 99
print(shallow_copy) # Output: [[99, 2], [3, 4]] (shared reference)
print(deep_copy) # Output: [[1, 2], [3, 4]] (independent copy)
List comprehensions are a concise way to create lists. They allow you to apply an expression to each item in an iterable and optionally filter items using a condition, all in a single line of code. Example:
numbers = [1, 2, 3, 4]
squares = [x ** 2 for x in numbers]
print(squares) # Output: [1, 4, 9, 16]
even_squares = [x ** 2 for x in numbers if x % 2 == 0]
print(even_squares) # Output: [4, 16]
The enumerate()
function in Python adds a counter to an iterable and returns an enumerate object, which can be converted into a list or looped over to get both the index and the value of each element. Example:
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(index, fruit)
# Output:
# 0 apple
# 1 banana
# 2 cherry
The zip()
function takes two or more iterables and aggregates them into tuples, where the first elements of each iterable are paired together, the second elements are paired together, and so on. Example:
names = ["Alice", "Bob", "Charlie"]
ages = [24, 30, 18]
zipped = zip(names, ages)
print(list(zipped)) # Output: [('Alice', 24), ('Bob', 30), ('Charlie', 18)]
==
: Checks for value equality. It returns True
if the values of the two objects are the same.is
: Checks for identity equality. It returns True
if the two objects are the same in memory (i.e., they refer to the same object). Example:
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # Output: True (values are equal)
print(a is b) # Output: False (they are two different objects)
Slicing is a way to access a subset of elements from an iterable (like a list, tuple, or string) using the syntax [start:stop:step]
. It allows you to extract parts of sequences. Example:
lst = [0, 1, 2, 3, 4, 5]
print(lst[1:4]) # Output: [1, 2, 3] (elements from index 1 to 3)
print(lst[:3]) # Output: [0, 1, 2] (elements from the start to index 2)
print(lst[::2]) # Output: [0, 2, 4] (every second element)
The all()
function returns True
if all elements in an iterable are True
(or if the iterable is empty). It short-circuits as soon as it finds a False
value. Example:
lst = [True, True, False]
print(all(lst)) # Output: False (since one element is False)
lst2 = [True, True]
print(all(lst2)) # Output: True
The any()
function returns True
if at least one element in an iterable is True
. If the iterable is empty or all elements are False
, it returns False
. Example:
lst = [False, False, True]
print(any(lst)) # Output: True (since at least one element is True)
lst2 = [False, False]
print(any(lst2)) # Output: False
*args
: Allows you to pass a variable number of non-keyword arguments to a function. Inside the function, args
is treated as a tuple.**kwargs
: Allows you to pass a variable number of keyword arguments to a function. Inside the function, kwargs
is treated as a dictionary. Example:
def example(*args, **kwargs):
print(args) # tuple of arguments
print(kwargs) # dictionary of keyword arguments
example(1, 2, 3, name="Alice", age=30)
# Output:
# (1, 2, 3)
# {'name': 'Alice', 'age': 30}
The sorted()
function in Python is used to return a sorted version of an iterable (like a list, tuple, or string). It does not modify the original iterable but returns a new sorted list. Example:
lst = [4, 2, 1, 3]
sorted_lst = sorted(lst)
print(sorted_lst) # Output: [1, 2, 3, 4]
The reversed()
function returns an iterator that yields the elements of an iterable in reverse order. It does not modify the original iterable. Example:
lst = [1, 2, 3]
reversed_lst = reversed(lst)
print(list(reversed_lst)) # Output: [3, 2, 1]
del
: Deletes an element at a specific index or an entire list. It doesn’t return the value of the element.remove()
: Removes the first occurrence of a value in a list. It raises an error if the value is not found.pop()
: Removes and returns an element at a specific index. If no index is provided, it removes and returns the last element. Example:
lst = [1, 2, 3, 4]
del lst[1] # Deletes element at index 1
print(lst) # Output: [1, 3, 4]
lst.remove(3) # Removes the first occurrence of 3
print(lst) # Output: [1, 4]
popped_item = lst.pop() # Removes and returns the last element
print(popped_item) # Output: 4
print(lst) # Output: [1]
The main differences between list
and tuple
are:
[]
, while tuples are defined using parentheses ()
. Example:
lst = [1, 2, 3]
lst[0] = 10 # This is allowed because lists are mutable
tup = (1, 2, 3)
# tup[0] = 10 # This will raise an error because tuples are immutable
A regular expression (regex) in Python is a sequence of characters that forms a search pattern. Python provides the re
module to work with regular expressions. It allows you to search, match, and manipulate strings using patterns. Example:
import re
text = "The rain in Spain"
match = re.search(r"\bS\w+", text)
print(match.group()) # Output: Spain
The with
statement is used for resource management, specifically for simplifying the management of file handling or other resources that need to be properly acquired and released. It ensures that resources are automatically cleaned up after their use, even if an exception occurs. Example:
with open("file.txt", "r") as file:
content = file.read()
print(content)
# The file is automatically closed when the block is exited, whether or not an exception occurs.
Python uses automatic memory management through reference counting and a garbage collector to reclaim memory used by objects that are no longer referenced. Python's memory management is built on the concept of object reference counting and uses a cyclic garbage collector to clean up memory. Example:
import gc
# You can manually trigger the garbage collector
gc.collect()
A frozenset
in Python is an immutable version of a set
. It is hashable, meaning it can be used as a key in a dictionary or added to another set. Once created, its elements cannot be modified. Example:
frozen = frozenset([1, 2, 3])
# frozen.add(4) # This will raise an error because frozensets are immutable