) (Conditional Statementsالتحكم الشرطي ⃣️1
.لتنفيذ كود بناًء على شرط صحيح أو خاطئ if statementsتستخدم Python
):المقارنات( Operators
يساوي o == :
ال يساوي o != :
أكبر من o > :
أصغر من o < :
:مثال
x = 10
if x > 5:
)"أكبر من print("x 5
elif x == 5:
)"يساوي print("x 5
else:
)"أصغر من print("x 5
) (Loopsالحلقات التكرارية ⃣️2
.تستخدم ألداء مهام متكررة على البيانات مثل القوائم أو النصوص
) (list, tuple, stringللتكرار على تسلسل عناصر for loop:
]"تفاح"" ,موز"" ,برتقال"[ = fruits
for fruit in fruits:
)print(fruit
تنفذ طالما الشرط صحيح while loop:
count = 0
while count < 3:
)print(count
count += 1
توليد أرقام للتكرار range() function:
for i in range(1, 6):
يطبع 1إلى print(i) # 5
) (Functionsالدوال ⃣️3
.تعريف :كتل كود قابلة إلعادة االستخدام تقوم بمهمة معينة
len(), sum(), sorted().مثل Built-in functions:
:إنشاء دوال خاصة
def greet(name):
"""ترحب بالمستخدم"""
" + nameمرحبًا" return
))"أحمد"(print(greet
:خصائص الدوال
Parameters.يمكن أن تحتوي على عدة o
.افتراضيًا Noneترجع return،إذا لم تحتوي على o
placeholder.كـ passيمكن استخدام o
:التوثيق
.بين ثالث عالمات اقتباس """ لشرح الدالة docstringاستخدام o
def add(a, b):
"""ترجع مجموع الرقمين"""
return a + b
يعرض التوثيق help(add) #
) (Variable Scopeنطاق المتغيرات ⃣️4
.متغيرات داخل دالة أو كتلة ،ال يمكن الوصول لها خارجها Local Variables:
.متغيرات معرفة في أعلى البرنامج ،يمكن الوصول لها من أي مكان Global Variables:
x = 10 # Global
def func():
y = 5 # Local
)print(x, y
)(func
ممكن الوصول print(x) #
غير معرفة هنا ، yخطأ # print(y) #
) (Exception Handlingالتعامل مع األخطاء ⃣️5
محاولة تنفيذ كود ومعالجة األخطاء عند وقوعها try-except:
try:
))" :أدخل رقمًا"(num = int(input
except ValueError:
)"!هذا ليس رقمًا صحيحًا"(print
تنفيذ كود عند عدم وقوع خطأ try-except-else:
try:
result = 10 / 2
except ZeroDivisionError:
)"!قسمة على صفر"(print
else:
):", resultالنتيجة"(print
ينفذ دائمًا try-except-else-finally: finally
try:
)"f = open("[Link]
except FileNotFoundError:
)"الملف غير موجود"(print
else:
)"تم فتح الملف بنجاح"(print
finally:
)"تم االنتهاء من العملية"(print
) (OOP – Objects & Classesالبرمجة الكائنية ⃣️6
.تحتوي على بيانات وسلوك Classنسخ من ):الكائنات( Objects
.قالب إلنشاء الكائنات ،يحدد الخصائص والوظائف ):الفئات( Classes
.خصائص البيانات للكائن Data Attributes:
.دوال داخل الكائن تتفاعل مع البيانات Methods:
.تهيئة خصائص الكائن عند إنشائه __init__ method:
:مثال
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def greet(self):
"سنة } {[Link]وعمري } {[Link]مرحبًا ،أنا"return f
)أحمد"p1 = Person("25 ,
))(print([Link]
self: .يشير للكائن نفسه ويتيح الوصول للخصائص والطرق داخله
الخالصة مع أمثلة ✅
المفهوم الوصف مثال مختصر
التحكم في تدفق البرنامج حسب
if/elif/else see above
الشرط
Loops تكرار العمليات على البيانات for/while
Functions كتل كود قابلة إلعادة االستخدام )(def greet
المفهوم الوصف مثال مختصر
Local vs
Variable Scope عالمي/محلي
Global
Exception
معالجة األخطاء try-except
Handling
class
OOP / Classes إنشاء كائنات وطرق خاصة بها
Person
Module 3 Summary: Python
Programming Fundamentals
Congratulations! You have completed this module. At this point, you know that:
Python conditions use “if” statements to execute code based on true/false conditions
created by comparisons and Boolean expressions.
Comparison operations require using comparison operators such as == (equal to), >
(greater than), and < (less than).
Python uses the "!=" operator to determine whether two values are not equal.
You can compare integers, strings, and floats.
Python branching directs program flow by using conditional statements (for example, if,
else, elif) to execute different code blocks based on conditions or tests.
You can use the "if" statement with conditions to define actions if true.
To perform actions when all previous conditions are false, you can use the "else"
statement without a condition.
The elif statement allows for additional checks only if the initial condition is false.
To execute various operations on Boolean values, we use Boolean logic operators.
Python loops are control structures that automate repetitive tasks and iterate over data
structures like lists or dictionaries.
The range() function generates a sequence of numbers with a specified start, stop, and
step value for loops in Python.
A for loop in Python iterates over a sequence, such as a list, tuple, or string, and
executes a block of code for each item in the sequence.
A while loop in Python executes a block of code as long as a specified condition remains
true.
Python functions are reusable code blocks that perform specific tasks, take input
parameters, and often return results, enhancing code modularity and reusability.
You may or may not have written the codes that are often included in functions.
Python has a set of built-in functions such as "len" to find the length of a sequence or
"sum" to find the total sum of a sequence.
The "sorted" function creates a new sorted list, while "sort" sorts items in the original list.
You can also create your own functions in Python.
To ensure clarity and organization and facilitate understanding and maintenance of the
code, developers must document functions using a documentation string enclosed in
three quotes.
The help command will return the documentation defined for a particular function.
A function can have multiple parameters.
If a function does not include a return statement, it returns None by default.
You can use the "pass" keyword in a function to indicate that it does nothing (a
placeholder for future code).
A function will usually perform more than one task.
In Python, the scope of a variable determines where you can access or modify that
variable. Global scope allows access from anywhere, while local scope restricts it to a
block or function.
In Python, a programmer defines a local variable within a specific block or function,
which can only be accessed or modified within that block or function.
In Python, a global variable is a variable defined at the top level of a program that any
part of the code can access or modify.
Exception handling in Python is a mechanism for managing and responding to errors
and exceptions that may occur during program execution, preventing them from
crashing the program.
In Python, you use the "try-except" statement to attempt a block of code and specify
alternative actions to execute if an error occurs, allowing you to handle exceptions.
In Python, you use the "try-except-else" statement to attempt a block of code, handle
exceptions in the "except" block, and execute code in the "else" block when no
exceptions occur.
Python developers use the "try-except-else-finally" statement to attempt a block of code,
catch exceptions in the "except" block, execute code in the "else" block when no
exceptions occur, and ensure that the "finally" block always runs, regardless of whether
exception was raised or not.
In Python, objects are instances of classes that encapsulate data and behavior, serving
as the foundation for creating and working with various data types and custom data
structures.
To determine the type of an object in Python, you can use the `type()` command.
Methods may modify an object’s internal state, but the object’s type usually remains the
same.
Classes in Python are blueprints for creating objects, defining their attributes and
methods, enabling code organization, and object-oriented programming.
Function "init" is a special method used to initialize data attributes.
We can create instances of a class in Python.
Data attributes consist of the data defining the objects.
Methods are functions that interact and change the data attributes.
The method has a function that requires the self as well as other parameters.
Glossary: Python Programming
Fundamentals
Welcome! This alphabetized glossary contains many of the terms you'll find within this course. This
comprehensive glossary also includes additional industry-recognized terms not used in course
videos. These terms are important for you to recognize when working in the industry, participating in
user groups, and participating in other certificate programs.
Term Definition
Refers to a concept or comparison outside the scope of the programming language
Analogy
itself, used to explain or relate one concept to another in a more understandable way.
Attributes in Python refer to the characteristics or properties of an object, and they
Attributes
can be accessed using dot notation.
Branching in Python is a process of altering the flow of a program based on
Branching
conditions, typically using if, elif, and else statements.
Comparison operators in Python are used to compare values and return Boolean
Comparison
results (True or False), including operators like == (equal),!= (not equal), < (less than),
operators
> (greater than), <= (less than or equal to), and >= (greater than or equal to).
Conditions in Python are used to make decisions in code, executing specific blocks
Conditions
of code based on whether a given expression evaluates to True or False.
In Python, "enumerate" is a built-in function that adds a counter to an iterable,
Enumerate
allowing you to loop through both the elements and their corresponding indices.
Exception handling in Python is a mechanism for gracefully managing and
Exception
responding to errors or exceptional conditions that may occur during program
handling
execution.
In Python, the term "explicitly" refers to performing an action or specifying
Explicitly
something in a clear, unambiguous, and direct manner.
For loops in Python are used for iterating over a sequence (such as a list, tuple, or
For loops string) or other iterable objects, executing a set of statements for each item in the
sequence.
Term Definition
Global Global variables in Python are variables defined outside of any function or block
variable and can be accessed and modified from any part of the code.
"Incremented" in Python means to increase the value of a variable by a specified
Incremented
amount, typically done using the += operator or by adding a fixed value.
In Python, "indent" refers to the use of whitespace at the beginning of a line to
Indent
signify the structure and scope of code blocks, such as loops and functions.
In Python, "indices" refer to the position or location of elements in a sequence, like
Indices
a string, list, or tuple, starting with 0 for the first element.
In Python, "iterate" means to repeatedly perform a set of operations or steps on
Iterate each item in a collection, such as a list, tuple, or dictionary, typically using loops or
iterators.
Local Local variables in Python are variables defined within a specific function or block of
variables code and are only accessible within that function or block.
Logic operators in Python are used to perform logical operations on Boolean
Logic
values, including operators like and (logical AND), or (logical OR), and not (logical
operators
NOT).
Loops in Python are constructs for repeating a block of code, enabling the
Loops
execution of the same code multiple times.
Parameters in Python are placeholders in a function definition, used to accept and
Parameters
work with values provided to the function when it is called.
Programming Programming fundamentals in Python involve variables, control structures,
Fundamentals functions, data structures, input/output, and error handling for building software.
The range function in Python generates a sequence of numbers that can be used
Range
for iterating in a loop and is typically used as range (start, stop, step), where it creates
function
numbers from start to stop-1 with the given step increment.
Term Definition
Scope of The "scope of a function" in Python refers to the region of code where a variable
function defined within that function is accessible or visible.
Sequences in Python are ordered collections of items that can include data types
Sequences
like strings, lists, and tuples, allowing for indexing and iteration.
In Python, "Syntax" refers to the set of rules that dictate how code must be written
Syntax and structured to be correctly interpreted by the Python interpreter. It includes correct
use of keywords, indentation, operators, and punctuation.
While loops in Python are used to repeatedly execute a block of code as long as a
While loops
specified condition is true.