introduction to Python
What is Python?
Python is a high-level, interpreted programming language known for its simplicity, readability,
and versatility. It was created by Guido van Rossum and first released in 1991.
Why Learn Python?
Easy to read and write
Widely used in web development, data science, machine learning, automation, and more
Huge community and plenty of libraries
Great for both beginners and experienced developers
Basic Features
Interpreted: Runs directly without compiling
Dynamically typed: No need to declare variable types
Object-oriented: Supports OOP features like classes and inheritance
Extensive standard library: Comes with lots of built-in modules
First Python Program
Python:
print("Hello, world!")
This prints a simple greeting to the screen. Python code is usually saved with a .py extension
and run using the Python interpreter.
Basic Concepts
Variables
Python:
name = "Alice"
age = 25
Data Types
int – integers: 10
float – decimals: 3.14
str – strings: "Hello"
bool – booleans: True, False
Conditional Statements
Python:
if age > 18:
print("Adult")
else:
print("Minor")
Loops
Python:
# For loop
for i in range(5):
print(i)
# While loop
count = 0
while count < 5:
print(count)
count += 1
Functions
Python:
def greet(name):
print("Hello", name)
greet("Developer")
Popular Python Libraries
numpy – numerical computations
pandas – data analysis
matplotlib – data visualization
requests – web requests
flask / django – web development
scikit-learn / tensorflow – machine learning
What Can You Build with Python?
Web applications
Desktop software
Automation scripts
Data analysis tools
AI and machine learning models
Games
Getting Started with Python
Step 1: Install Python
Download & Install Python:
1. Go to the official site: https://python.org
2. Download the latest version for your OS (Windows, macOS, or Linux).
3. Install Python (example: in Windows*)
Step 2: Check Python Installation
Open your terminal or command prompt (cmd) and type:
CMD:
python –version
You should see something like:
Python 3.x.x
If not, try:
CMD:
python3 –version
Step 3: Write Your First Python Code
Option 1: Using the Python Shell
Just type python in your terminal, and you’ll enter an interactive shell.
Python:
print("Hello, Python!")
Hello, Python!
Exit with exit() or Ctrl + Z / Ctrl + D.
Option 2: Using a Python File
1. Create a new file called your_name.py
2. Add the following code:
Python:
print("Hello, Python!")
(Save As... x.txt to x.py)
3. Run it from your terminal:
CMD:
python hello.py
(python x.py)
Step 4: Choose a Code Editor or IDE
Some popular choices:
VS Code – Lightweight and powerful
PyCharm – Full-featured Python IDE
Thonny – Great for beginners
Jupyter Notebook – Perfect for data science
variables
What is a Variable in Python?
A variable is like a container in Python that stores data. It has a name and holds a value.
Creating Variables
You don’t need to declare the type — Python figures it out for you.
Python:
# Integer variable
age = 19
# Float variable
price = 19.99
# String variable
name = "Shay"
# Boolean variable
is_online = True
Printing Variables
Python:
print(name) # Output: Shay
print(age + 5) # Output: 30
Variable Naming Rules
Must start with a letter or underscore (_)
Cannot start with a number
Can only contain letters, numbers, and underscores
Python is case-sensitive (Name and name are different)
✅ Valid:
Python:
user_name = "Souhail"
_user2 = 2025
❌ Invalid:
Python:
2user = "Souhail" # Error: starts with a number
user-name = "Developer" # Error: hyphen is not allowed
Multiple Assignment
You can assign multiple values in one line:
Python:
x, y, z = 1, 2, 3
Or assign the same value:
Python:
a = b = c = 100
Type Checking
Python:
print(type(age)) # <class 'int'>
print(type(price)) # <class 'float'>
print(type(name)) # <class 'str'>
What is Type Checking?
In Python, every variable has a type, such as:
int for integers (like 1, 2, 100)
float for decimal numbers (like 3.14, 9.99)
str for strings (like "hello", "Developer")
If you want to check the type of a variable, you can use the built-in function type().
Example:
Python:
age = 21
price = 19.99
name = "Cormac"
print(type(age)) # Output: <class 'int'>
print(type(price)) # Output: <class 'float'>
print(type(name)) # Output: <class 'str'>
Explanation:
type(age) checks what type of value age is holding — it returns <class 'int'>
because 21 is an integer.
type(price) returns <class 'float'> because 19.99 is a decimal number.
type(name) returns <class 'str'> because "Cormac" is a string (text).
Why Use type()?
Helps debug your code
Confirms data types before performing operations (e.g., math operations on numbers
only)
Useful when you're working with user input, which is always a string by default
Data Types
In Python, data types represent the kind of value a variable holds. Python automatically detects
the type when you assign a value.
Numeric Types
Used for numbers.
➤ int — Integer
Whole numbers (positive, negative, or zero)
Python:
x = 10
print(type(x)) # <class 'int'>
➤ float — Floating Point Number
Decimal numbers
Python:
pi = 3.14
print(type(pi)) # <class 'float'>
➤ complex — Complex Number
Used in mathematics, contains real and imaginary parts
Python:
z = 2 + 3j
print(type(z)) # <class 'complex'>
Text Type
➤ str — String
A sequence of characters (text)
Python:
name = "Souhail"
print(type(name)) # <class 'str'>
Boolean Type
➤ bool — Boolean
Only two values: True or False
Python:
is_active = True
print(type(is_active)) # <class 'bool'>
Sequence Types
list — Mutable Sequence
A list can contain items of different data types
Elements can be added, removed, or changed
Python:
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple
fruits.append("orange") # Add an item
fruits[1] = "mango" # Change an item
print(fruits) # OP: ['apple', 'mango', 'cherry', 'orange']
tuple — Ordered, unchangeable collection
Python:
colors = ("red", "green", "blue")
print(type(colors)) # <class 'tuple'>
range — Sequence of numbers (often used in loops)
Python:
nums = range(5)
print(type(nums)) # <class 'range'>
Mapping Type
➤ dict — Dictionary: key-value pairs
Python:
person = {"name": "Meliodas", "age": 3000}
print(type(person)) # <class 'dict'>
Set Types
➤ set — Unordered, unique items
Python:
my_set = {1, 2, 3}
print(type(my_set)) # <class 'set'>
➤ frozenset — Immutable version of a set
Python:
f_set = frozenset([1, 2, 3])
print(type(f_set)) # <class 'frozenset'>
Binary Types
Binary types are used to store and work with binary data — like data from files (especially
non-text files like images, audio, video, etc.).
Python provides three main types for binary data:
Type Description
bytes Immutable sequence of bytes
bytearray Mutable version of bytes
memoryview Used to access buffer without copying
When to Use These?
bytes: When you read binary files and don’t need to change them.
bytearray: When you need to manipulate binary data.
memoryview: For efficient data access/modification without making copies (used in high-
performance or large data processing).
bytes
A bytes object is immutable (cannot be changed).
It stores a sequence of integers between 0 and 255.
Commonly used when reading binary data from files.
Example:
Python:
b = bytes(4)
print(b) # Output: b'\x00\x00\x00\x00' (4 zero bytes)
print(type(b)) # Output: <class 'bytes'>
You can also create it from a list of integers:
Python:
b2 = bytes([65, 66, 67])
print(b2) # Output: b'ABC'
bytearray
Similar to bytes, but mutable — you can change the contents.
Useful when you need to modify binary data.
Example:
Python:
ba = bytearray([1, 2, 3, 4])
print(ba) # Output: bytearray(b'\x01\x02\x03\x04')
ba[0] = 100 # Change the first byte
print(ba) # Output: bytearray(b'd\x02\x03\x04')
memoryview
Allows you to access and modify data in bytes or bytearray without copying it.
Very efficient for working with large data.
Example:
Python:
ba = bytearray([10, 20, 30, 40])
mv = memoryview(ba)
print(mv[1]) # Output: 20
mv[1] = 99 # Modify using memoryview
print(ba) # Output: bytearray(...) — changed to 99
None Type
Represents absence of a value
Python:
value = None
print(type(value)) # <class 'NoneType'>
Summary Table
Data Type Example
int x = 10
float pi = 3.14
complex z = 1 + 2j
str name = "Alice"
bool is_valid = True
list nums = [1, 2, 3]
tuple t = (1, 2)
range r = range(5)
dict d = {"key": "value"}
set s = {1, 2, 3}
frozenset fs = frozenset([1, 2])
bytes b = bytes(4)
NoneType x = None
Conditional Statements
What Are Conditional Statements?
Conditional statements let your program make decisions. You can run different blocks of code
depending on whether a condition is True or False.
Python provides:
if statement
elif (else if) statement
else statement
if Statement
Runs a block of code only if the condition is true.
Syntax:
Python:
if condition:
# code block
Example:
Python:
age = 20
if age >= 18:
print("You are an adult.")
elif Statement
Stands for "else if". It checks another condition if the previous one was False.
Syntax:
Python:
if condition1:
# block 1
elif condition2:
# block 2
Example:
Python:
marks = 75
if marks >= 90:
print("Grade A")
elif marks >= 70:
print("Grade B")
else Statement
Runs a block of code if none of the previous if or elif conditions are true.
Syntax:
Python:
if condition1:
# block 1
elif condition2:
# block 2
else:
# block 3
Example:
Python:
score = 40
if score >= 90:
print("Excellent")
elif score >= 50:
print("Passed")
else:
print("Failed")
Using Logical Operators
Combine multiple conditions using:
and → True if both conditions are True
or → True if one of the conditions is True
not → Inverts the condition
Example:
Python:
age = 25
country = "USA"
if age > 18 and country == "USA":
print("Eligible to vote in the USA")
Nested if Statements
You can put one if statement inside another.
Example:
Python:
age = 20
has_id = True
if age >= 18:
if has_id:
print("Access granted")
else:
print("ID required")
Tips for Writing Conditional Statements
Use indentation (4 spaces or a tab) — it's required in Python!
Keep conditions clear and readable
Avoid deeply nested conditions — they make code harder to read
Use elif instead of multiple ifs when conditions are related
Loops
What are Loops?
Loops allow you to execute a block of code multiple times — either a specific number of times
or while a condition remains true.
Python provides two main types of loops:
1. for loop
2. while loop
We also use break and continue to control the loop flow.
for Loop
Used to iterate over a sequence (like a list, tuple, string, or range()).
Syntax:
Python:
for variable in sequence:
# code block
Example:
Python:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Looping with range()
Python:
for i in range(5):
print(i)
while Loop
Repeats a block as long as a condition is True.
Syntax:
Python:
while condition:
# code block
Example:
Python:
count = 0
while count < 5:
print("Count is:", count)
count += 1
⚠ Be careful: while loops can become infinite loops if the condition never becomes False.
break Statement
Used to exit a loop early when a condition is met.
Example:
Python:
for i in range(10):
if i == 5:
break
print(i)
continue Statement
Skips the current iteration and moves to the next one.
Example:
Python:
for i in range(5):
if i == 2:
continue
print(i)
else with Loops
Both for and while loops can have an else clause that runs after the loop finishes, only if it
didn’t exit via break.
Example:
Python:
for i in range(3):
print(i)
else:
print("Loop finished without break.")
Summary Table
Loop Type When to Use
for When you know how many times to loop or want to iterate through items
while When looping based on a condition
break To stop the loop early
continue To skip part of the loop and continue
else To run a block when loop ends normally
Function
What is a Function?
A function is a block of code that performs a specific task. You can call (or use) that block of
code whenever you need it, instead of repeating the same code multiple times.
Defining a Function
Use the def keyword to define a function.
Syntax:
Python:
def function_name(parameters):
# code block
return result # (optional)
Example:
Python:
def greet(name):
print("Hello, " + name + "!")
greet("Souhail")
greet("Developer")
Return Statement
Functions can return values using the return keyword.
Example:
Python:
def add(a, b):
return a + b
result = add(5, 3)
print(result)
Function with Default Parameters
You can give default values to parameters. If the caller doesn’t provide a value, the default is
used.
Example:
Python:
def greet(name="Guest"):
print("Hello, " + name)
greet() # uses default
greet("Shay") # uses provided value
Keyword Arguments
You can pass arguments using parameter names:
Python:
def student_info(name, age):
print(f"Name: {name}, Age: {age}")
student_info(age=20, name=" Gwynevere")
Arbitrary Arguments
If you don’t know how many arguments will be passed:
args: for multiple positional arguments
python:
def total(*numbers):
return sum(numbers)
print(total(1, 2, 3, 4)) # 10
kwargs: for multiple keyword arguments
python:
def show_info(**info):
for key, value in info.items():
print(f"{key}: {value}")
show_info(name="Shay", age=19)
Nested Functions
Functions can be defined inside other functions:
Python:
def outer():
def inner():
print("Inner function")
inner()
outer()
Lambda Functions (Anonymous functions)
Useful for small, one-line functions.
Python:
square = lambda x: x * x
print(square(5)) # 25
Benefits of Using Functions
Avoid code repetition
Make code easier to read and maintain
Break problems into smaller, manageable parts
Improve reusability
Summary
Feature Description
def Defines a function
return Returns a result from the function
*args / **kwargs Accept variable numbers of arguments
Default parameters Provide fallback values
Lambda function Small anonymous function
Email:
souhaillaghchim.dev@proton.me
Blogger:
https://souhaillaghchimdev.blogspot.com/