Python Basics with Examples:
- Basic Syntax
- Variables:
x = 10
- Print:
print("Hello, World!")
- Comments: Single-line
# This is a comment
, Multi-line'''This is a multi-line comment'''
- Data Types
- Integers:
x = 42
- Floats:
y = 3.14
- Booleans:
is_happy = True
- Strings:
greeting = "Hello"
- String Manipulation
- Concatenation:
"Hello" + " " + "World"
- Formatting:
f"Hello, {name}!"
- Length:
len("Hello")
- Upper / Lower:
"Hello".upper()
/"Hello".lower()
- Lists
- Initialization:
my_list = [1, 2, 3]
- Access:
my_list[0]
- Append:
my_list.append(4)
- Remove:
my_list.remove(1)
- Length:
len(my_list)
- Slice:
my_list[1:3]
- Tuples
- Initialization:
my_tuple = (1, 2, 3)
- Access:
my_tuple[0]
- Sets
- Initialization:
my_set = {1, 2, 3}
- Add:
my_set.add(4)
- Remove:
my_set.remove(1)
- Dictionaries
- Initialization:
my_dict = {'a': 1, 'b': 2, 'c': 3}
- Access:
my_dict['a']
- Set:
my_dict['d'] = 4
- Remove:
del my_dict['a']
- Keys:
my_dict.keys()
- Conditionals
- if:
if x > 10:
- elif:
elif x > 5:
- else:
else:
- Loops
- For:
for i in range(5):
- While:
while x < 10:
- Functions
- Definition:
def my_function(arg1, arg2):
- Call:
my_function(1, 2)
- Return:
return result
- Classes
- Definition:
class MyClass:
- Initialization:
def __init__(self, attr1, attr2):
- Methods:
def my_method(self, arg):
- Inheritance:
class ChildClass(ParentClass):
- Exceptions
- Try / Except:
try:
risky_operation()
except Exception as e:
print(f"Caught an exception: {e}")
- Raise:
raise ValueError("Invalid value")
- List Comprehensions
- Basic:
[x * 2 for x in my_list]
- With condition:
[x * 2 for x in my_list if x > 3]
- Lambda Functions
- Basic:
lambda x: x * 2
- With multiple arguments:
lambda x, y: x + y
- File I/O
- Read
with open("file.txt", "r") as f:
content = f.read()
- Write
with open("file.txt", "w") as f:
f.write("Hello, World!")
Here are some common Python interview questions:
- Python 3 uses
print()
as a function, while Python 2 usesprint
as a statement. - Python 3 has better Unicode support with strings as Unicode by default.
- Division in Python 3 returns a float; in Python 2, it returns an integer (use
//
for integer division in Python 3). - Python 3 uses
input()
for user input, while Python 2 usesraw_input()
.
- List: mutable, ordered collection, allows duplicates; syntax:
[1, 2, 3]
- Tuple: immutable, ordered collection, allows duplicates; syntax:
(1, 2, 3)
- Set: mutable, unordered collection, no duplicates; syntax:
{1, 2, 3}
- Shallow copy creates a new object but doesn’t recursively copy nested objects, while a deep copy creates a new object and copies nested objects recursively.
- Shallow copy:
copy.copy()
, deep copy:copy.deepcopy()
List comprehensions are a concise way to create lists using a single line of code. They can include a loop and a conditional expression:
[x**2 for x in range(1, 11) if x % 2 == 0]
- Mutable: can be modified after creation (e.g., lists, sets, dictionaries)
- Immutable: cannot be modified after creation (e.g., strings, tuples, integers, floats, booleans)
try:
# Code that might raise an exception
except ExceptionType as e:
# Handle the exception
- “is” checks if two variables point to the same object in memory.
- “==” checks if the values of the objects are equal.
Decorators are functions that modify the behavior of other functions or methods without permanently modifying their code. They are used with the “@” syntax:
The Global Interpreter Lock (GIL) is a mechanism that prevents multiple native threads from executing Python bytecodes concurrently. It ensures only one thread runs in the interpreter at a time, which can limit the performance of CPU-bound and multi-threaded programs.
map()
, filter()
, and reduce()
:
map(function, iterable)
: applies a function to all items in an input list.filter(function, iterable)
: filters items from an iterable based on a function returning True/False.reduce(function, iterable)
: applies a rolling computation to an iterable’s items, reducing them to a single value.
- *args: used to pass a variable number of non-keyword (positional) arguments to a function.
- **kwargs: used to pass a variable number of keyword arguments to a function.
- Function: a block of reusable code that performs a specific task and is not tied to a specific class.
- Method: a function that is associated with a specific class and can access or modify the class’s properties.
__init__
: a special method called when an object is created; it initializes the object’s attributes.self
: a reference to the
Inheritance in Python: Inheritance is a way to create a new class that is a modified version of an existing class. The new class is called the derived (or child) class, and the existing class is the base (or parent) class. Inheritance provides code reusability and modularity.
PEP 8 is the Python Enhancement Proposal that provides a style guide for writing Python code. It includes guidelines for naming conventions, indentation, whitespace usage, and other best practices to improve the readability and consistency of Python code.
Virtual environments in Python are isolated spaces that allow you to install packages and dependencies specific to a project without affecting the global Python installation. They help maintain separate dependencies for different projects, avoiding conflicts. You can create a virtual environment using venv
or virtualenv
.
- “return”: used to return a value from a function and exit the function immediately.
- “yield”: used to create a generator; it returns a value from the function, but the function’s state is preserved, and execution can be resumed from the same point later.
- Multi-threading: multiple threads run concurrently within a single process, sharing the same memory space. Limited by the GIL in CPython.
- Multi-processing: multiple processes run independently, each with its own memory space and Python interpreter. Suitable for CPU-bound tasks.
A generator is a special type of iterator that produces values on-the-fly using the yield
keyword. Generators are memory-efficient because they don’t store all items in memory at once but generate each item as needed.
A context manager is an object that sets up and tears down a context for a block of code. It is typically used with the with
statement to ensure that resources like files or network connections are properly acquired and released. Context managers are created using classes with __enter__()
and __exit__()
methods or with the contextlib
module.