Python Basics with Examples:

 
  1. Basic Syntax
  • Variables: x = 10
  • Print: print("Hello, World!")
  • Comments: Single-line # This is a comment, Multi-line '''This is a multi-line comment'''
 
  1. Data Types
  • Integers: x = 42
  • Floats: y = 3.14
  • Booleans: is_happy = True
  • Strings: greeting = "Hello"
 
  1. String Manipulation
  • Concatenation: "Hello" + " " + "World"
  • Formatting: f"Hello, {name}!"
  • Length: len("Hello")
  • Upper / Lower: "Hello".upper() / "Hello".lower()
 
  1. 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]
 
  1. Tuples
  • Initialization: my_tuple = (1, 2, 3)
  • Access: my_tuple[0]
 
  1. Sets
  • Initialization: my_set = {1, 2, 3}
  • Add: my_set.add(4)
  • Remove: my_set.remove(1)
 
  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()
 
  1. Conditionals
  • if: if x > 10:
  • elif: elif x > 5:
  • else: else:
 
  1. Loops
  • For: for i in range(5):
  • While: while x < 10:
 
  1. Functions
  • Definition: def my_function(arg1, arg2):
  • Call: my_function(1, 2)
  • Return: return result
 
  1. Classes
  • Definition: class MyClass:
  • Initialization: def __init__(self, attr1, attr2):
  • Methods: def my_method(self, arg):
  • Inheritance: class ChildClass(ParentClass):
  1. Exceptions
  • Try / Except:
				
					try:
    risky_operation()
except Exception as e:
    print(f"Caught an exception: {e}")

				
			
  • Raise: raise ValueError("Invalid value")
  1. List Comprehensions
  • Basic: [x * 2 for x in my_list]
  • With condition: [x * 2 for x in my_list if x > 3]
 
  1. Lambda Functions
  • Basic: lambda x: x * 2
  • With multiple arguments: lambda x, y: x + y
 
  1. 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!")

				
			

python banner at the top of the page

Here are some common Python interview questions:

What are the key differences between Python 2 and Python 3?

  • Python 3 uses print() as a function, while Python 2 uses print 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 uses raw_input().

What is the difference between a list, tuple, and set?

  • 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}

Explain the difference between a shallow copy and a deep copy in Python.

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

What are list comprehensions and how can they be used?

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]

What are the main differences between mutable and immutable data types in Python?

  • Mutable: can be modified after creation (e.g., lists, sets, dictionaries)
  • Immutable: cannot be modified after creation (e.g., strings, tuples, integers, floats, booleans)

How do you handle exceptions in Python? Can you provide an example of a try-except block?

try:

# Code that might raise an exception

except ExceptionType as e:

# Handle the exception

What is the difference between "is" and "==" in Python?

  • “is” checks if two variables point to the same object in memory.
  • “==” checks if the values of the objects are equal.

What are decorators in Python, and how do they work?

Decorators are functions that modify the behavior of other functions or methods without permanently modifying their code. They are used with the “@” syntax:

 
@decorator def
my_function():
# Function code

What is the GIL (Global Interpreter Lock), and how does it affect multi-threading in Python?

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.

Explain the difference between the map(), filter(), and reduce() functions.

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.

What are *args and **kwargs, and when should they be used in Python?

  • *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.

What is the difference between a function and a method in Python?

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

What is the purpose of init and self in Python classes?

  • __init__: a special method called when an object is created; it initializes the object’s attributes.
  • self: a reference to the

Explain how inheritance works in Python.

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.

What is PEP 8 and why is it important in Python development?

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.

Explain the concept of virtual environments in Python.

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.

What is the difference between "yield" and "return" in Python?

  • “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.

Describe the main differences between multi-threading and multi-processing in Python.

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

Explain how a generator works in Python.

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.

What is a context manager and how do you use the "with" statement?

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.

If you want to set up Python environment with an IDE such as PyCharm, refer to my download section: UbuntuWindows

Social Share: