Python Comprehensive Resource Document
Python Comprehensive Resource Document
1 INTRODUCTION TO PYTHON
Resource Document
Informatics Club – Al Hanane II, Preselection Exam. Python is a high-level, interpreted programming language known
for its readability and simplicity. It supports multiple
This resource document is provided as a reference for the Python programming paradigms, including procedural, object-oriented,
programming questions in the exam. It includes detailed and functional programming.
explanations of Python's core concepts, built-in functions, and
standard libraries to help you navigate the exercises effectively. • Interpreted Language: Python code is executed line by
line by the interpreter.
If you're transitioning from languages like C# or Java, this • Dynamic Typing: Variables are dynamically typed,
document also highlights key differences to support your meaning their type is determined at runtime.
understanding. Use this guide wisely to assist with solving
problems, but remember that your ability to apply the concepts
matters most. 2 VARIABLES AND DATA TYPES
3 Operators....................................................................................2
4 Control Flow Statements ...........................................................3 2.2 DATA TYPES
5 Functions ....................................................................................3 2.2.1 Numeric Types
6 Modules and Packages ...............................................................4 • int: Integer numbers.
• float: Floating-point numbers.
7 Object-Oriented Programming (OOP) .......................................4
• complex: Complex numbers with real and imaginary parts.
8 Built-in Functions ......................................................................4
a = 5 # int
9 Standard Libraries .....................................................................5 b = 3.14 # float
c = 2 + 3j # complex
10 File I/O Operations .................................................................6
11 Advanced Topics .....................................................................7 2.2.2 Boolean Type
• bool: True or False.
12 Comparison with C# and Java ...............................................7
1
is_active = True 4. Division: / (always returns a float)
5. Floor Division: // (returns an integer result)
2.2.3 Sequence Types 6. Modulus: %
• list: Ordered, mutable collection. 7. Exponentiation: **
fruits = ["apple", "banana", "cherry"]
x = 10
• tuple: Ordered, immutable collection. y = 3
print(x / y) # 3.333...
coordinates = (10, 20) print(x // y) # 3
print(x % y) # 1
• range: Represents an immutable sequence of numbers. It is print(x ** y) # 1000
its own object.
numbers = range(5) # 0 to 4 3.2 COMPARISON OPERATORS
1. Equal: ==
2.2.4 Text Type 2. Not Equal: !=
• str: String of Unicode characters. 3. Greater Than: >
message = "Hello, World!" 4. Less Than: <
5. Greater Than or Equal To: >=
2.2.5 Set Types 6. Less Than or Equal To: <=
• set: Unordered collection of unique elements.
unique_numbers = {1, 2, 3} 3.3 LOGICAL OPERATORS
• frozenset: Immutable version of a set. It won’t be used in • Logical AND: and
this exam. • Logical OR: or
• Logical NOT: not
2.2.6 Mapping Type
dict: Collection of key-value pairs.
3.4 ASSIGNMENT OPERATORS
person = {"name": "Alice", "age": 30}
• Simple Assignment: =
• Add AND: +=
• Subtract AND: -=
3 OPERATORS • Multiply AND: *=
• Divide AND: /=, etc.
2
4 CONTROL FLOW STATEMENTS
"""Docstring (optional)"""
# Code block
return value # (optional)
5 FUNCTIONS
for key, value in kwargs.items():
print(f"{key}: {value}")
display_info(name="Alice", age=30, city="Paris")
# Output:
Functions are defined using the def keyword. # name: Alice
# age: 30
def function_name(parameters):
3
# city: Paris # Creating an object
person1 = Person("Alice", 30)
Here, **kwargs allows the function to accept any number of person1.greet()
keyword arguments.
7.2 INHERITANCE
5.3 ANONYMOUS FUNCTIONS (LAMBDAS) class Employee(Person):
square = lambda x: x ** 2 def __init__(self, name, age, employee_id):
print(square(5)) # 25 super().__init__(name, age)
self.employee_id = employee_id
8 BUILT-IN FUNCTIONS
self.age = age
def greet(self):
print(f"Hello, I'm {self.name}.")
Python provides numerous built-in functions:
4
8.1 TYPE CONVERSION • help(obj): Displays the help page.
• int(x): Converts x to an integer.
• float(x): Converts x to a float. 8.6 MEMORY AND OBJECT MANAGEMENT
• str(x): Converts x to a string. • id(obj): Returns the unique identifier.
• bool(x): Converts x to a boolean. • hash(obj): Returns the hash value.
• list(x), tuple(x), set(x), dict(x)
5
9.3 DATETIME MODULE try:
# Code that may raise an exception
Work with dates and times. result = 10 / 0
except ZeroDivisionError as e:
from datetime import datetime, timedelta print("Cannot divide by zero!")
now = datetime.now() except Exception as e:
five_days_from_now = now + timedelta(days=5) print(f"An error occurred: {e}")
else:
# Executes if no exceptions are raised
print("Division successful.")
9.4 OS MODULE finally:
Interact with the operating system. # Always executes
print("Execution complete.")
import os Custom Exceptions: Define your own exception classes.
os.getcwd()
os.listdir('.') class MyCustomError(Exception):
pass
6
11 ADVANCED TOPICS 12.2 OBJECT-ORIENTED CONCEPTS
• Everything is an Object: Even functions and classes are
objects.
11.1 GENERATORS • Multiple Inheritance: Python supports multiple
Functions that return an iterator using yield. inheritance.
def fibonacci(n):
a, b = 0, 1
while a < n:
12.3 ACCESS MODIFIERS
yield a No strict enforcement of public, private, protected. Uses naming
a, b = b, a + b conventions instead.
for num in fibonacci(10):
print(num)
display()
12.7 MEMORY MANAGEMENT
• Automatic garbage collection.
12 COMPARISON WITH C# AND JAVA • No need for manual memory allocation or deallocation.