Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

Python Comprehensive Resource Document

A comprehensive resource document to get ready to learn python very easily, informatics club alhanane 2.

Uploaded by

tempsama88
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Python Comprehensive Resource Document

A comprehensive resource document to get ready to learn python very easily, informatics club alhanane 2.

Uploaded by

tempsama88
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Python Comprehensive

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

TABLE OF CONTENTS 2.1 VARIABLES


• No need to declare variables before assigning values.
Table of contents ...............................................................................1 • Variable names are case-sensitive.
1 Introduction to Python ...............................................................1
counter = 10
2 Variables and Data Types..........................................................1 name = "Alice"

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.

3.1 ARITHMETIC OPERATORS


1. Addition: +
2. Subtraction: -
3. Multiplication: *

2
4 CONTROL FLOW STATEMENTS
"""Docstring (optional)"""
# Code block
return value # (optional)

4.1 CONDITIONAL STATEMENTS


5.1 DEFAULT PARAMETERS
if condition1:
# Code block def greet(name, message="Hello"):
elif condition2: print(f"{message}, {name}!")
# Code block
else: greet("Alice") # Hello, Alice!
# Code block

4.2 LOOPS 5.2 VARIABLE-LENGTH ARGUMENTS


4.2.1 For Loop 5.2.1 *args (Non-Keyword Arguments)
Iterates over a sequence. *args collects positional arguments passed to the function into a
for item in iterable:
tuple. Useful when the number of arguments is unknown or
# Code block variable.
Example:
Example:
for i in range(1, 6):
def add_numbers(*args):
print(i)
return sum(args)
print(add_numbers(1, 2, 3)) # Output: 6
4.2.2 While Loop print(add_numbers(4, 5, 6, 7, 8)) # Output: 30
Repeats as long as a condition is true. Here, *args allows the function to accept any number of positional
arguments.
while condition:
# Code block
5.2.2 **kwargs (Keyword Arguments)
4.2.3 Loop Control Statements **kwargs collects keyword arguments passed to the function into a
• break: Exits the nearest enclosing loop. dictionary.
• continue: Skips the rest of the current loop iteration, and Useful when you want to handle named arguments dynamically.
goes back to the start.
• pass: Does nothing; acts as a placeholder. Example:
def display_info(**kwargs):

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

6 MODULES AND PACKAGES 7.3 METHOD OVERRIDING


class Animal:
6.1 IMPORTING MODULES def sound(self):
print("Some sound")
import math
print(math.sqrt(16)) # 4.0 class Dog(Animal):
def sound(self):
print("Bark")

6.2 FROM IMPORT SYNTAX


from math import pi, sin
print(pi) # 3.141592653589793
7.4 ENCAPSULATION
• Python doesn't have private variables in the same way as
C# or Java.
• Prefixing an attribute with _ indicates it's intended for
7 OBJECT-ORIENTED PROGRAMMING internal use.
• Prefixing with __ (double underscore) triggers name
(OOP) mangling1.
class MyClass:
7.1 CLASSES AND OBJECTS def __init__(self):
self._internal_var = 42
class Person: self.__private_var = 99
def __init__(self, name, age):
self.name = name

8 BUILT-IN FUNCTIONS
self.age = age

def greet(self):
print(f"Hello, I'm {self.name}.")
Python provides numerous built-in functions:

1Name mangling is a mechanism in Python that alters the names of


certain class attributes to make them harder to accidentally override or
access from outside the class.

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)

8.7 OTHER USEFUL FUNCTIONS


8.2 MATHEMATICAL FUNCTIONS • any(iterable): Returns True if any element is True.
• abs(x): Absolute value. • all(iterable): Returns True if all elements are True.
• round(x, n): Rounds x to n decimal places. • zip(*iterables): Aggregates elements from each iterable.
• pow(x, y): Returns x raised to the power y.
• divmod(a, b): Returns a tuple (a // b, a % b). names = ["Alice", "Bob"]
ages = [25, 30]
for name, age in zip(names, ages):

8.3 SEQUENCE FUNCTIONS print(f"{name} is {age} years old.")


• len(s): Length of s.
• max(s): Maximum value.
• min(s): Minimum value. 9 STANDARD LIBRARIES
• sum(s): Sum of elements.
• sort(s): Returns a sorted list. Python's standard library offers a rich set of modules.
• reversed(s): Returns an iterator in reverse order.
• enumerate(s): Returns an iterator of tuples (index, value). 9.1 MATH MODULE
Advanced mathematical functions.
8.4 INPUT/OUTPUT FUNCTIONS import math
• print(*objects, sep2=' ', end='\n') math.factorial(5) # 120
math.log(10, 10) # 1.0
• input(prompt)

8.5 OBJECT INTROSPECTION 9.2 RANDOM MODULE


Generate random numbers.
• type(obj): Returns the type of obj.
• isinstance(obj, cls): Checks if obj is an instance of cls. import random
• dir(obj): List of attributes and methods. random.randint(1, 100)
random.choice(['apple', 'banana', 'cherry'])

2 Specifies the separator between the values being printed. By default, it


is set to a space character.

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

9.5 SYS MODULE


System-specific parameters and functions. 10 FILE I/O OPERATIONS
import sys
sys.argv # Command-line arguments
sys.platform 10.1 READING FILES
with open('data.txt', 'r') as file:
content = file.read()
9.6 JSON MODULE
Work with JSON data.
import json 10.2 WRITING FILES
data = {'name': 'Alice', 'age': 30}
json_str = json.dumps(data) with open('output.txt', 'w') as file:
data_loaded = json.loads(json_str) file.write("Hello, World!")

9.7 REGULAR EXPRESSIONS (RE MODULE) 10.3 CSV FILES


import csv
Pattern matching in strings. with open('data.csv', 'r') as csvfile:
reader = csv.reader(csvfile)
import re for row in reader:
pattern = r'\d+' print(row)
re.findall(pattern, 'There are 24 apples and 42 bananas')
NOTE: Please do not use Regex in this test.

9.8 EXCEPTION HANDLING


Handle runtime errors gracefully.

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)

12.4 EXCEPTION HANDLING


11.2 DECORATORS Similar try, except, finally blocks, but syntax differs.
Functions that modify the behavior of other functions.
def decorator_function(original_function):
12.5 STANDARD LIBRARIES
def wrapper_function(*args, **kwargs): Python's standard library is extensive and includes many modules
# Code before
result = original_function(*args, **kwargs)
that might require external libraries in C# or Java.
# Code after
return result
return wrapper_function 12.6 FUNCTIONAL PROGRAMMING
@decorator_function
First-class functions, lambdas, list comprehensions make
def display(): functional programming more idiomatic.
print("Display function ran.")

display()
12.7 MEMORY MANAGEMENT
• Automatic garbage collection.
12 COMPARISON WITH C# AND JAVA • No need for manual memory allocation or deallocation.

12.1 SYNTAX DIFFERENCES


• No Semicolons: Python doesn't require semicolons at the
end of statements.
• Indentation: Indentation defines code blocks instead of
braces {}.
• Dynamic Typing: Variables don't need explicit type
declarations.

You might also like