Why Python?
Python is one of the most popular programming languages today. Its popularity comes from a set of
powerful features that make it easy to learn, flexible, and widely applicable.
1. Dynamic Typing
Python uses dynamic typing, which means you do not need to declare the type of a variable before using
it. The interpreter assigns the type automatically at runtime.
x = 10 # integer
x = "Hello" # now x is a string
This makes coding faster, but you need to be careful because type errors may appear during execution.
2. Interpreter
Python is an interpreted language, not a compiled one. The code runs line by line directly through the
Python interpreter.
Advantage: Easy to test and debug quickly.
Disadvantage: Slightly slower compared to compiled languages like C++ or Java.
3. Open Source
Python is free and open source.
Anyone can download and use it without cost.
Developers around the world contribute to its growth by building new libraries, frameworks, and
tools.
4. Extensible
Python is extensible:
You can write performance-critical parts of your program in C or C++ and then connect them with
Python.
This makes Python suitable for small scripts as well as large, high-performance applications.
5. Database Support
Python provides strong support for databases.
Built-in libraries and third-party modules allow connection to:
o MySQL
o PostgreSQL
o SQLite
o MongoDB
This makes it an excellent choice for web development and enterprise applications.
6. Simple Syntax
Python has a clear and simple syntax that is easy to read and write.
The code looks like plain English.
Example:
for i in range(3):
print("Welcome to Python")
This code prints the sentence three times, using minimal and clean syntax.
📌 Summary:
Python is dynamic, interpreted, open source, extensible, database-friendly, and very simple to use. That’s
why it is loved by beginners and professionals alike.
🔹 Variables in Python
A variable is simply a name that refers to a value stored in memory. In Python, variables are very easy to
use because you do not need to declare their type explicitly.
1. Declaring Variables
x = 10 # integer
name = "Ali" # string
pi = 3.14 # float
is_active = True # boolean
2. Dynamic Typing
x=5
print(x) # Output: 5
x = "Hello"
print(x) # Output: Hello
3. Variable Naming Rules
✅ Allowed:
Letters (a-z, A-Z), digits (0-9), underscore _.
❌ Not Allowed:
Starting with digits, using spaces, or reserved keywords.
age = 20 # valid
user_name = "Ali" # valid
2name = "Sara" # ❌ invalid
for = 5 # ❌ invalid
4. Multiple Assignments
a, b, c = 1, 2, 3
x=y=z=0
5. Constants
PI = 3.14159
MAX_USERS = 100
6. Deleting Variables
x = 100
del x
📌 Summary:
Variables are used to store data.
Python uses dynamic typing.
Follow naming rules.
Multiple assignment is supported.
Use uppercase names for constants.
🔹 Strings in Python
A string is a sequence of characters enclosed in either single quotes ' ' or double quotes " ". Strings are one
of the most commonly used data types in Python.
1. Creating Strings
s1 = 'Hello'
s2 = "World"
s3 = '''This is
a multi-line
string'''
2. String Indexing and Slicing
word = "Python"
print(word[0]) # P
print(word[-1]) # n
print(word[0:4]) # Pyth
print(word[2:]) # thon
3. String Operations
# Concatenation
print("Hello" + " " + "World")
# Repetition
print("Hi! " * 3)
# Length
print(len("Python"))
4. String Methods
txt = " hello world "
print(txt.upper())
print(txt.lower())
print(txt.strip())
print(txt.replace("world", "Python"))
print(txt.split())
5. String Formatting
name = "Ali"
age = 20
print(f"My name is {name} and I am {age} years old.")
6. Escape Characters
print("Hello\nWorld")
print("She said: \"Hi\"")
🔹 Numbers in Python
Numbers are one of the fundamental data types in Python. They are used to represent numeric values.
Python provides three main numeric types:
1. Types of Numbers
🔸 Integers (int)
Whole numbers (positive, negative, or zero).
x = 10
y = -5
z=0
🔸 Floating Point Numbers (float)
Decimal numbers or real numbers with fractions.
pi = 3.14
temperature = -7.5
🔸 Complex Numbers (complex)
Numbers in the form a + bj, where a is the real part and b is the imaginary part.
c = 3 + 4j
print(c.real) # 3.0
print(c.imag) # 4.0
2. Arithmetic Operations
Python supports all common arithmetic operations:
a = 10
b=3
print(a + b) # 13 (Addition)
print(a - b) # 7 (Subtraction)
print(a * b) # 30 (Multiplication)
print(a / b) # 3.333... (Division)
print(a // b) # 3 (Floor division)
print(a % b) # 1 (Modulus)
print(a ** b) # 1000 (Exponentiation: 10^3)
3. Type Conversion
You can convert between numeric types and even from strings:
x=5
print(float(x)) # 5.0 (int → float)
y = 3.14
print(int(y)) # 3 (float → int)
z = "100"
print(int(z)) # 100 (string → int)
4. Math Functions
Python provides the math module with many useful functions:
import math
print(math.sqrt(16)) # 4.0 (Square root)
print(math.pow(2, 3)) # 8.0 (Power)
print(math.pi) # 3.141592653589793
print(math.factorial(5)) # 120
5. Random Numbers
The random module is used for generating random values:
import random
print(random.randint(1, 10)) # Random integer between 1 and 10
print(random.random()) # Random float between 0 and 1
6. Mixing Numbers and Strings
In Python, you cannot directly add an integer (int) to a string (str). Doing so will raise a TypeError because
Python does not automatically convert between numbers and text.
age = 20
msg = "I am " + age # ❌ Error: can only concatenate str (not "int") to str
✅ The solution is to use type conversion with str():
age = 20
msg = "I am " + str(age)
print(msg) # Output: I am 20
Or, use f-strings (simpler and cleaner):
age = 20
print(f"I am {age}") # Output: I am 20
🔹 Input in Python
In Python, you can take input from the user using the built-in input() function.
The function always returns the user’s input as a string.
You can then convert it to other types if needed (int, float, etc.).
1. Basic Input
name = input("Enter your name: ")
print("Hello, " + name)
📌 Whatever the user types will be stored as a string.
2. Numeric Input
Since input() returns a string, you need to convert it when expecting numbers:
age = int(input("Enter your age: ")) # convert to integer
height = float(input("Enter your height: ")) # convert to float
print(f"You are {age} years old and {height} meters tall.")
3. Example: Simple Calculator
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Sum =", a + b)
✅ This program asks the user for two numbers, adds them, and prints the result.
4. Important Notes
Always remember: input() returns a string by default.
If you want to do math, use type conversion (int(), float()).
If the user enters invalid data (like typing letters instead of numbers), Python will raise an error.
📘 Lists in Python
🔹 Introduction
A list in Python is an ordered collection that can store multiple items in a single variable.
Lists are dynamic (you can add or remove elements anytime).
Lists can contain different data types (numbers, strings, booleans, or even other lists).
my_list = [1, "hello", 3.14, True]
print(my_list)
# [1, 'hello', 3.14, True]
🔹 Creating a List
numbers = [1, 2, 3, 4, 5]
words = ["apple", "banana", "cherry"]
mixed = [1, "hello", 3.5, False]
🔹 Accessing Elements
Using index (starts from 0):
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[2]) # cherry
Negative index (from the end):
print(fruits[-1]) # cherry
🔹 Modifying a List
fruits = ["apple", "banana", "cherry"]
fruits[1] = "orange"
print(fruits)
# ['apple', 'orange', 'cherry']
🔹 List Methods
1. append() → Add item at the end
fruits.append("mango")
2. insert(index, value) → Insert item at specific position
fruits.insert(1, "kiwi")
3. remove(value) → Remove item
fruits.remove("apple")
4. pop(index) → Remove by index
fruits.pop(0) # removes first item
5. sort() → Sort the list
numbers = [4, 1, 3, 2]
numbers.sort()
print(numbers) # [1, 2, 3, 4]
6. reverse() → Reverse order
numbers.reverse()
🔹 Looping through a List
fruits = ["apple", "banana", "cherry"]
for f in fruits:
print(f)
🔹 Concatenation (joining two lists)
list1 = [1, 2, 3]
list2 = [4, 5, 6]
new_list = list1 + list2
print(new_list) # [1, 2, 3, 4, 5, 6]
Repetition:
nums = [1, 2]
print(nums * 3) # [1, 2, 1, 2, 1, 2]
🔹 Copying a List
⚠️ Using = does not copy, it only references the same list.
copy()
list1 = [1, 2, 3]
list2 = list1.copy()
list2.append(4)
print(list1) # [1, 2, 3]
print(list2) # [1, 2, 3, 4]
Slicing
list1 = [10, 20, 30]
list2 = list1[:]
🔹 Difference between List and Array
Array (in other languages): must store same data type.
List (in Python): can store different data types and is dynamic.
import array
my_array = array.array('i', [1, 2, 3]) # integers only
🔹 List Comprehension
A shorter way to create lists using loops in one line.
numbers = [x**2 for x in range(5)]
print(numbers)
# [0, 1, 4, 9, 16]
✅ Summary
Lists are ordered, dynamic, and flexible.
Can store different types of data.
Support many built-in methods (append, remove, sort, …).
Can be concatenated and repeated.
Copy using copy() or slicing ([:]).
More flexible than arrays.
📘 Tuples in Python
🔹 Introduction
A tuple is a collection in Python used to store multiple items in a single variable.
Tuples are similar to lists, but they are immutable (cannot be changed after creation).
Tuples are defined using parentheses ( ).
🔹 Creating a Tuple
# Empty tuple
empty_tuple = ()
# Tuple with values
numbers = (1, 2, 3, 4, 5)
# Tuple with mixed data types
mixed = (1, "Hello", 3.5, True)
# Single element tuple (note the comma!)
single = (5,)
🔹 Accessing Tuple Elements
my_tuple = (10, 20, 30, 40)
print(my_tuple[0]) # 10
print(my_tuple[-1]) # 40
print(my_tuple[1:3]) # (20, 30)
🔹 Tuple is Immutable
Unlike lists, you cannot change, add, or remove elements in a tuple.
my_tuple = (1, 2, 3)
# my_tuple[0] = 10 # ❌ Error
🔹 Tuple Methods
Tuples have only two methods:
my_tuple = (1, 2, 2, 3)
print(my_tuple.count(2)) # 2
print(my_tuple.index(3)) # 3
📘 Comparison: List vs Tuple
🔹 1. Creation
# List
my_list = [1, 2, 3]
# Tuple
my_tuple = (1, 2, 3)
print(type(my_list)) # <class 'list'>
print(type(my_tuple)) # <class 'tuple'>
🔹 2. Mutability
List: Mutable (can be changed).
Tuple: Immutable (cannot be changed).
# List
my_list = [1, 2, 3]
my_list[0] = 10
print(my_list) # [10, 2, 3]
# Tuple
my_tuple = (1, 2, 3)
# my_tuple[0] = 10 # ❌ Error
🔹 3. Adding & Removing Elements
# List
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # [1, 2, 3, 4]
my_list.remove(2)
print(my_list) # [1, 3, 4]
# Tuple
my_tuple = (1, 2, 3)
# my_tuple.append(4) # ❌ Error
# my_tuple.remove(2) # ❌ Error
🔹 4. Methods
# List
my_list = [1, 2, 2, 3]
print(my_list.count(2)) # 2
my_list.sort()
print(my_list) # [1, 2, 2, 3]
# Tuple
my_tuple = (1, 2, 2, 3)
print(my_tuple.count(2)) # 2
print(my_tuple.index(3)) # 3
🔹 5. Performance
Tuples are faster than lists when iterating.
import time
list_test = [i for i in range(1000000)]
start = time.time()
for item in list_test:
pass
print("List Time:", time.time() - start)
tuple_test = tuple(list_test)
start = time.time()
for item in tuple_test:
pass
print("Tuple Time:", time.time() - start)
🔹 6. Use in Dictionary Keys
Lists: ❌ cannot be used as dictionary keys.
Tuples: ✅ can be used as dictionary keys.
# Tuple as key ✅
my_dict = {(1, 2): "value"}
print(my_dict[(1, 2)]) # value
# List as key ❌
# my_dict = {[1, 2]: "value"} # Error
🟦 1. Dictionary in Python ()القواميس
✅ التعريف
( القاموسdict) في بايثون هوmapping type بيخزن البيانات في شكل،key-value pairs.
الـkey الزم يكونimmutable (زي: str, int, tuple) بينما الـvalue ( ممكن تكون أي نوعlist, dict, object…).
✅ إنشاءDictionary
# Empty dictionary
d1 = {}
# Dictionary with data
d2 = {"name": "Youssef", "age": 20, "skills": ["Python", "C++"]}
✅ الوصول وتعديل البيانات
print(d2["name"]) # Youssef
d2["age"] = 21 # Update value
d2["country"] = "Egypt" # Add new key-value pair
⚠️ لو طلبتkey → مش موجودKeyError.
حلها باستخدام:
print(d2.get("salary", "Not Found"))
✅ العمليات األساسية
# حذف
d2.pop("age") # بحذف بالـkey
del d2["country"] # زيpop
d2.clear() # يمسح كل العناصر
# طول القاموس
len(d2)
# فحص وجودkey
"skills" in d2
✅ ( التكرارIteration)
for key in d2: # بترجع المفاتيح
print(key)
for key, value in d2.items(): # بترجعkey + value
print(key, value)
for value in d2.values(): # بترجع القيم
print(value)
✅ Methods متقدمة ومفيدة
# دمج قواميس
d1 = {"a": 1, "b": 2}
d2 = {"b": 3, "c": 4}
d1.update(d2) # {'a':1, 'b':3, 'c':4}
# نسخ
copy_d = d1.copy()
# تعيينdefault value لو المفتاح مش موجود
d = {}
d.setdefault("name", "Unknown") # {'name': 'Unknown'}
# Dictionary Comprehension
squares = {x: x**2 for x in range(5)}
# {0:0, 1:1, 2:4, 3:9, 4:16}
✅ مالحظات احترافية
1. استخدامget() أوdefaultdict بدل ما يحصلKeyError.
2. استخدامdict comprehension بدلfor loop عادي لو الهدف تحويل أو فلترة.
3. مفاتيح القاموس الزم تكونhashable → يعني ما ينفعش تستخدمlist كمفتاح.
4. ترتيب اإلدخال3.7 ( من بايثونinsertion order) بيتم االحتفاظ بيه.
🟦 2. Loops in Python
✅ النوعين الرئيسيين
1. for loop → للتكرار علىsequence (list, dict, string…).
2. while loop → للتكرار طالما الشرطTrue.
✅ For Loop
for i in range(5):
print(i)
range(start, stop, step)
يشتغل على أيiterable:
for ch in "Python":
print(ch)
✅ While Loop
x=0
while x < 5:
print(x)
x += 1
⚠️ → لو نسيت تعدل الشرطinfinite loop.
✅ التحكم في التدفق
for i in range(10):
if i == 5:
continue # 5 يتخطى
if i == 8:
break # 8 يوقف عند
else:
print("Loop finished without break")
الـelse في الـloop بيتنفذ لو اللوب خلص بدون ما يحصلbreak.
✅ Nested Loops
for i in range(3):
for j in range(2):
print(i, j)
✅ Loop + else مع البحث
nums = [1, 3, 5, 7]
target = 4
for n in nums:
if n == target:
print("Found!")
break
else:
print("Not Found")
✅ Comprehensions ( بديل للـloop )التقليدي
List comprehension:
squares = [x**2 for x in range(5)]
Dictionary comprehension:
d = {x: x**2 for x in range(5) if x % 2 == 0}
Set comprehension:
unique = {ch for ch in "programming"}
✅ مالحظات احترافية
1. استخدامcomprehensions أفضل منloops فلترة البيانات/ أسرع وأكثر( التقليدية لو الهدف تحويلPythonic).
2. ما تكثرشnested loops األفضل تستخدم، itertools ( زيproduct, combinations).
3. لو عايزperformance استخدم،عالي جدًاgenerator expressions بدلcomprehensions العادية.
في بايثون بشكل احترافي ومتقدم يناسب كتابك ،مع أمثلة عملية (Conditional Statements) +خلينا نعمل شرح الحاالت الشرطية
.مالحظات للمستوى المحترف
🟦 Conditional Statements in Python
الفكرة العامة ✅
Boolean (True/False).الحاالت الشرطية بتسمحلك تنفّذ كود معين بنا ًء على تحقق شرط
:بايثون بتو ّفر
if
if ... else
if ... elif ... else
) (Ternary Operatorتعبير شرطي
1. if statement
x = 10
if x > 5:
)"print("x is greater than 5
.ينفّذ البلوك Trueالشرط بيتقيّم → لو
).المسافة البادئة( indentationالبلوك بيعتمد على
2. if ... else
x=3
if x % 2 == 0:
)"print("Even
else:
)"print("Odd
.بينفّذ أحد البلوكين فقط
3. if ... elif ... else
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print("Grade:", grade)
elif = else + if.
أول شرط، بيتحقق بالترتيب من فوق لتحتTrue يقفل الباقي.
4. Ternary Operator (One-liner if)
age = 18
status = "Adult" if age >= 18 else "Minor"
print(status)
صيغة مختصرة: value_if_true if condition else value_if_false
مفيد في التعبيرات القصيرة.
5. Nested Conditions ()متداخلة
x = 10
if x > 0:
if x % 2 == 0:
print("Positive Even")
else:
print("Positive Odd")
else:
print("Non-positive")
⚠️ األفضل تجنّب التداخل الكتير → استبداله بـlogical operators (and, or).
6. استخدام المقارنات المركبة
:بايثون بتميزها عن لغات تانية
x = 15
if 10 < x < 20:
)"print("x is between 10 and 20
): (x > 10) and (x < 20دي زي
.أوضح وأقرب للرياضيات
) (Logical Operatorsالمنطق الشرطي 7.
Trueكل الشروط الزم تكون → and
يكفي شرط واحد → or
عكس القيمة → not
x, y = 5, 10
if x > 0 and y > 0:
)"print("Both positive
if x == 5 or y == 0:
)"print("Condition met
if not (x > 10):
)"print("x is not greater than 10
==و isالفروق بين 8.
.يقارن القيم → ==
.يقارن الهوية (نفس الكائن في الذاكرة) → is
]a = [1,2
]b = [1,2
)القيم متساوية( print(a == b) # True
)مراجع مختلفة( print(a is b) # False
مالحظات احترافية ✅
(performance + readability).احرص على ترتيب الشروط من األعم → لألخص 1.
2. &&/||.أوضح وأفضل من )(chained comparisonsاستخدام المقارنات المتسلسلة
.بتركيب منطقي واحد nested ifلتقليل التعقيد ،حاول تستبدل 3.
4. if-elif.بدل كثرة pattern matchingللـ ) Python 3.10ابتدا ًء من( match-caseاستخدم
)9. Pattern Matching (Python 3.10+
if-elif:بديل متطور للـ
"command = "start
match command:
case "start":
)"print("System starting...
case "stop":
)"print("System stopping...
case _:
)"print("Unknown command
else).زي( defaultمعناها _
if-elif.أقوى بكتير من → tuples, dicts, classesينفع كمان تشتغل على
؟ dictionariesوالـ loopsتحب أجهزلك كمان تمارين +حلول على الحاالت الشرطية زي ما عملنا مع الـ
You said:
اشرح الدوال
ChatGPT said:
✨ تمام يا يوسف
التعريف ،األنواع ،البرامترز ( في بايثون بأسلوب احترافي لشخص متقدم ،مع التفاصيل الكاملة ) (Functionsخلينا نشرح الدوال
).إلخ … ، decoratorsالـ scopeالمختلفة ،الـ
🟦 Functions in Python
تعريف ✅
.هي كتلة كود قابلة إلعادة االستخدام بتنُفّذ مهمة معينة ) (functionالدالة
.وتخلي الكود منظم أكتر ) (DRY – Don’t Repeat Yourselfبتساعدك تقلل التكرار
1. إنشاء دالة أساسية
def greet():
print("Hello, Python!")
التعريف يبدأ بالكلمة المفتاحيةdef.
اسم الدالة → الزم يتبع قواعد الـidentifiers.
الكود داخلها يتحدد بالـindentation.
2. استدعاء الدالة
greet()
3. الدوال مع البرامترزParameters
def greet(name):
print(f"Hello, {name}!")
greet("Youssef")
البرامتر هو متغير يستقبل قيمة عند استدعاء الدالة.
4. ( القيم االفتراضيةDefault Parameters)
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() # Hello, Guest
greet("Ali") # Hello, Ali
5. ( إرجاع القيمReturn)
def add(a, b):
return a + b
result = add(5, 3)
print(result)
return بيرجع قيمة → تقدر تخزنها أو تستخدمها.
لو ما فيشreturn → الدالة بترجعNone.
6. األنواع المختلفة للبرامترز
بايثون بيدعم5 أنواع أساسية:
1⃣ Positional Arguments
def divide(a, b):
return a / b
print(divide(10, 2)) # 5.0
2⃣ Keyword Arguments
print(divide(b=2, a=10)) # 5.0
3⃣ Default Arguments
()زي ما شفنا قبل شوية.
4⃣ Variable-length Arguments
*args → يقبل أي عدد من القيم.
**kwargs → يقبل أي عدد منkey-value pairs.
def show(*args, **kwargs):
print("Args:", args)
print("Kwargs:", kwargs)
show(1, 2, 3, name="Youssef", age=20)
5⃣ Positional-only & Keyword-only (Python 3.8+)
def func(a, /, b, *, c):
print(a, b, c)
func(1, 2, c=3) # صحيح
# func(a=1, b=2, c=3) ❌ (a الزمpositional )فقط
7. ( نطاق المتغيراتScope)
→ المتغيرات اللي بتتحدد داخل دالةlocal scope.
→ اللي براهاglobal scope.
x = 10 # global
def test():
x = 5 # local
print("Inside:", x)
test()
print("Outside:", x)
استخدامglobal أوnonlocal لتعديل القيم:
count = 0
def increment():
global count
count += 1
8. ( الدوال المجهولةLambda Functions)
دوال قصيرة بدونdef.
square = lambda x: x**2
print(square(5)) # 25
غالبًا معmap, filter, sorted:
nums = [1, 2, 3, 4]
evens = list(filter(lambda n: n % 2 == 0, nums))
print(evens) # [2, 4]
9. Higher-Order Functions
الدوال في بايثونfirst-class citizens: تتبعت كـ، ممكن تتحط في متغيرparameter أو ترجع من دالة،.
def apply(func, x):
return func(x)
print(apply(lambda x: x**3, 2)) # 8
10. Closures
دالة داخلية تحتفظ بالـvariables حتى بعد انتهاء الدالة الخارجية.
def outer(x):
def inner(y):
return x + y
return inner
add5 = outer(5)
print(add5(10)) # 15
11. Decorators
دوال بتعدّل أو تزود وظيفة لدوال أخرى بدون تغيير الكود األصلي.
def decorator(func):
def wrapper():
print("Before function")
func()
print("After function")
return wrapper
@decorator
def say_hello():
print("Hello!")
say_hello()
✅ مالحظات احترافية
1. (األفضل تخلي الدالة تعمل حاجة واحدة فقطSingle Responsibility Principle).
2. ( سمي الدوال بأسماء واضحة ومعبرةsnake_case).
3. لو الدالة طويلة → قسمها لدوال أصغر.
4. استخدمdocstrings للتوثيق.
12. ( التوثيقDocstrings)
def add(a: int, b: int) -> int:
"""
Add two numbers.
Args:
a (int): First number.
b (int): Second number.
Returns:
int: The sum of a and b.
"""
return a + b
باستخدامhelp(add) هتظهر المعلومات.
تقدر تضيفtype hints زيa: int لزيادة الوضوح.