Python: From Darkness to Dawn (.DOCX)
Python: From Darkness to Dawn (.DOCX)
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.
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
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
CMD:
python –version
Python 3.x.x
If not, try:
CMD:
python3 –version
Just type python in your terminal, and you’ll enter an interactive shell.
Python:
print("Hello, Python!")
Hello, Python!
Python:
print("Hello, Python!")
(python x.py)
Step 4: Choose a Code Editor or IDE
Some popular choices:
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
✅ 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
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:
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"
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
Python:
x = 10
print(type(x)) # <class 'int'>
Decimal numbers
Python:
pi = 3.14
print(type(pi)) # <class 'float'>
Python:
z = 2 + 3j
print(type(z)) # <class 'complex'>
Text Type
➤ str — String
Python:
name = "Souhail"
print(type(name)) # <class 'str'>
Boolean Type
➤ bool — Boolean
Python:
is_active = True
print(type(is_active)) # <class 'bool'>
Sequence Types
list — Mutable Sequence
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']
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'>
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.).
Type Description
bytes Immutable sequence of bytes
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
Example:
Python:
b = bytes(4)
print(b) # Output: b'\x00\x00\x00\x00' (4 zero bytes)
print(type(b)) # Output: <class 'bytes'>
Python:
b2 = bytes([65, 66, 67])
print(b2) # Output: b'ABC'
bytearray
Example:
Python:
ba = bytearray([1, 2, 3, 4])
print(ba) # Output: bytearray(b'\x01\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
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
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
else:
print("Failed")
Python:
age = 25
country = "USA"
Nested if Statements
You can put one if statement inside another.
Example:
Python:
age = 20
has_id = True
else:
print("ID required")
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.
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"]
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
⚠ 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)
Example:
Python:
for i in range(3):
print(i)
else:
print("Loop finished without break.")
Summary Table
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)
Example:
Python:
def greet(name="Guest"):
print("Hello, " + name)
Python:
def student_info(name, age):
print(f"Name: {name}, Age: {age}")
Arbitrary Arguments
If you don’t know how many arguments will be passed:
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
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:
[email protected]
Blogger:
https://souhaillaghchimdev.blogspot.com/