0% found this document useful (0 votes)
41 views66 pages

Python - One Sheet

Python sheet

Uploaded by

Yosra Yaseen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views66 pages

Python - One Sheet

Python sheet

Uploaded by

Yosra Yaseen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 66

``

Declaring Variables ‫انواع المتغيرات‬

In Python, variables are declared by simply assigning a value to a name using the = operator.
variable_name = value

Integer Floating-point String Boolean List


Whole (float): Strings are True or Lists are ordered
numbers. Numbers with sequences of False. collections that can hold
‫عدد صصحيح‬ decimal points. characters ‫قمية‬ multiple values of
‫عدد كسري‬ ‫حرف او‬ ‫منطقية‬ different types.
‫مجموع‬ True = 1 ‫القائمة‬
‫احرف‬ False = 0

X=10 X=10.9 X=”Ahmad” X= True X=[]


Id= 6 Salary = 500.9 Y=’Sami’ X= False Y=[3,4,7]
X=’a’ X=1 Names=[‘Ali’,’Sami’,’Wael’]
Y=0
Note:
In Python, you do not need to declare the type of the variable before assigning a value. Python
automatically detects the type based on the value assigned.
‫ بايثون يكتشف النوع تلقائًيا استناًدا‬.‫ ال تحتاج إلى إعالن نوع المتغير قبل تعيين قيمة له‬،‫في بايثون‬
.‫إلى القيمة المعينة‬

Variable Naming Rules: ‫قواعد تسمية المتغيرات‬


While naming variables in Python, there are certain rules to follow:
 A variable name can only contain letters (a-z, A-Z), numbers (0-9), and underscores (_).
)_( ‫ والشرطات السفلية‬،)9-0( ‫ واألرقام‬،)a-z, A-Z( ‫يمكن أن يحتوي اسم المتغير على الحروف‬
 A variable name cannot start with a number (e.g., 2x is invalid).
‫غير صالح‬x 2 ،‫ال يمكن أن يبدأ اسم المتغير برقم (على سبيل المثال‬
 Python is case-sensitive, meaning name, Name, and NAME are considered different
variables.
‫ تعتبر متغيرات مختلفة‬NAME ‫ و‬Name ‫ و‬name ‫ مما يعني أن‬،‫بايثون حساسة لحالة األحرف‬
 Avoid using Python reserved words (also called keywords) like if, else, class, import, etc.
``

‫ و‬else ‫ و‬if ‫تجنب استخدام الكلمات المحجوزة في بايثون (المعروفة أيًضا بالكلمات الرئيسية) مثل‬
.‫ وما إلى ذلك‬import ‫ و‬class

:EXAMPLES
Code Valid/UnValid
age = 25 Valid
_age = 30 Valid
2years = 10 Invalid: Cannot start with a number
def = 50 Invalid: 'def' is a reserved word
First name = ‘Ali’ Invalid: Cannot contain space

Type Conversion:‫تحويل المتغيرات من نوع الى نوع اخر‬


Sometimes, you may need to convert between different data types. Python provides built-in
functions for this:
 int() – Converts to an integer
 float() – Converts to a float
 str() – Converts to a string
 bool() – cConvert to a boolean

Error Types in Type Conversion in Python: ‫أنواع األخطاء في تحويل البيانات في بايثون‬
1. ValueError: This occurs when trying to convert a value to an inappropriate data type. For
example, trying to convert a string containing non-numeric characters into an integer.
‫ محاولة‬،‫ على سبيل المثال‬.‫يحدث عندما يتم محاولة تحويل قيمة إلى نوع بيانات غير مناسب‬
.‫تحويل سلسلة نصية تحتوي على أحرف إلى عدد صحيح‬
X= int(‘a43’)
2. TypeError: This occurs when trying to convert a data type that is not compatible with the
target type. For example, attempting to convert a list into an integer.
،‫ على سبيل المثال‬.‫يحدث عندما يتم محاولة تحويل نوع بيانات غير قابل للتحويل إلى نوع آخر‬
‫محاولة تحويل قائمة إلى عدد صحيح‬
int([1, 2, 3])
``

To avoid these errors, it's important to ensure that the data being converted is compatible with
the target type and follows the appropriate syntax.
‫ يجب التأكد من أن البيانات التي يتم تحويلها قابلة للتحويل بشكل صحيح إلى‬،‫لتجنب هذه األخطاء‬
.‫النوع المستهدف‬

Example:
CODE OUTPUT
x= int("abc") Raises ValueError ‫ال يمكن تحويل النص الى عدد‬
print(x)
num = int("hello") Raises ValueError ‫ال يمكن تحويل النص الى عدد‬
print(num)
num = float("10.5.6") Raises ValueError ‫ال يمكن تحويل القائمة الى‬
print(num) ‫عدد‬
x= float("123.45") 123.45
print(x)
x= int("123abc") Raises ValueError ‫ال يمكن تحويل النص الى عدد‬
print(x)
x= int("") Raises ValueError ‫ال يمكن تحويل النص الى عدد‬
print(x)
x= str(True) True
print(x)
result = True + "1" TypeError: unsupported ‫ال يمكن جمع عدد الى متغير‬
print(result) operand type(s) for +: 'bool' and ‫ من نوع‬bool
'str'
x= 'a' TypeError: can only concatenate ‫ال يمكن جمع عدد الى نص‬
y=2 str (not "int") to str
z=x+y
print(z)
x= 'a' +'b' ab
print(x)
x= 3 7.3
y= 4.3
z=x+y
print(z)
result = True + 5 6 ‫ بواحد‬True ‫هنا تم اعتبار قيمة‬
print(result)
x= bool(1) True
print(x)
x= bool(0) False
print(x)
x= bool(120) True ‫عند تحويل اي قيمة غير‬
print(x) ‫ فان قيمته‬bool ‫الصفر الى‬
``

True ‫ستكون‬
x= bool('a') True ‫عند تحويل اي قيمة غير‬
print(x) ‫ فان قيمته‬bool ‫الصفر الى‬
True ‫ستكون‬
print(float(99) / 100) 0.99

print(99 / 100) 0.99


Printing ‫الطباعة‬
 The print() function is a built-in function in Python used to display output to the user.

Example:
Code Output
print("Hello, World!") Hello, World!
print("Python", "is", "fun!") Python is fun!
print('a') a ،‫بشكل افتراضي‬
print('b') b )(print ‫تضيف‬
‫حرف السطر‬
‫) في‬n\( ‫الجديد‬
‫نهاية النص الذي‬
‫تطبعه )يتم‬
‫النزول لسطر‬
‫جديد تلقائيا بعد‬
‫استخدام االمر‬
)print
print('a\n') a
print('b')
b
print('My name is \nPython') My name is
Python
print('a', end='') ab ‫ يتم‬،‫في بايثون‬
print('b') ‫ استخدام‬end= ‫لتغير‬
‫النص الذي يتم إضافته‬
‫في نهاية السطر عند‬
‫استخدام الدالة‬
print()
print('a', end='*') a*b ‫ يتم‬،‫في بايثون‬
print('b') ‫ استخدام‬end= ‫لتغير‬
‫النص الذي يتم إضافته‬
‫في نهاية السطر عند‬
‫استخدام الدالة‬
print()
print("Hello,", end=" ") Hello, World! ‫ يتم‬،‫في بايثون‬
print("World!") =end ‫استخدام‬
‫لتغير النص الذي يتم‬
``

‫إضافته في نهاية‬
‫السطر عند استخدام‬
)(print ‫الدالة‬
x= 100 x=100
print('x=', x)
x= 100 100 x= 100
print(x,'x=', x)
x= 100 100 x=
print(x,'x=')
name = "Alice" Name: Alice Age: 25
age = 25
print("Name:", name, "Age:", age)
print(f"Name: {name}, Age: {age}") Name: Alice, Age: 25
print("The sum of 5 and 3 is", 5 + 3) The sum of 5 and 3 is 8
print("The sum of 5 and 3 is", “5 + 3”) The sum of 5 and 3 is 3+5 ‫اي شي يوضع بين‬
‫" " يطبع مثل ما‬
‫هو بغض النظر‬
‫عما بداخلة‬
x = 10 Debug: x =10
print("Debug: x =", x)
print("Result:", 3 * 7) Result:21
print("Result:", 'x' + 'y') Result:xy
print("Result:", 'x' + 3) ERROR ‫ال يمكن جمع عدد‬
‫الى نص‬
x = 10 x
print(‘x’)
x = 10 10
print(x)
x = 10 x=10 y=20
y=20
print('x=',x,'y=',y)
x = 10 x=10 y=20*
y=20
print('x=',x,'y=',y,end="* ")
x = 10 x=10 y=20
y=20 Finish
print('x=',x,'y=',y')
print('Finish')
x = 10 x=10 y=20 Finish
y=20
print('x=',x,'y=',y, end=' ')
print('Finish')
x = 20 6.66
y=3 6
``

r1=x/y
r2=int(x/y)
print(r1)
print(r2)

Type(object):
Returns the type of the object

Code Output
print(type(10)) <class 'int'>
print(type(3.14)) <class 'float'>
print(type("hello")) <class 'str'>
print(type([1, 2, 3])) <class 'list'>

Input from the User in Python ‫عمليات االدخال من لوحة‬


‫المفاتيح‬
By default, the input() function returns a string (even if the user enters a number). This is
where casting comes into play.

‫() سلسلة نصية (حتى إذا أدخل المستخدم‬input ‫ ُترِج ع دالة‬،‫بشكل افتراضي‬
.‫) لتغيير نوع البيانات إذا لزم األمر‬Casting( ‫ وهنا يأتي دور التحويل‬.)‫رقًم ا‬

Example:
name = input("Enter your name: ") ‫هنا سيتم ادخال قيمة من لوحة المفاتيح وستخزن القيمة‬
‫ علما ان نوع القمية التي سيتم‬, name ‫داخل المتغير‬
string ‫ادخالها ستكون من نوع نص‬
mark = input("Enter your mark: ") ‫هنا سيتم ادخال قيمة من لوحة المفاتيح وستخزن القيمة‬
‫ علما ان نوع القمية التي سيتم‬, mark ‫داخل المتغير‬
string ‫ادخالها ستكون من نوع نص‬
Casting Input Data Types ‫تحويل نوع القيم المدخلة‬
Sometimes, you may want the input to be of a specific data type, such as an integer or a float.
Since input() returns a string, you need to cast the input to the desired type using the appropriate
type conversion functions.
( ‫) أو عدد عشري‬integer( ‫ مثل عدد صحيح‬،‫احياًنا قد تحتاج إلى أن يكون اإلدخال من نوع بيانات معين‬
‫ فإنه يجب تحويل اإلدخال إلى النوع المطلوب‬،)string( ‫() ُترِج ع قيمة نصية‬input ‫ نظًر ا ألن دالة‬.)float
‫باستخدام دوال تحويل النوع المناسبة‬
mark1 = input("Enter Mark1:") Enter Mark1:
mark2 = input("Enter Mark2:") 10
sum = mark1 + mark2 Enter Mark2:
‫``‬

‫)‪print("Sum=", sum‬‬ ‫‪20‬‬


‫‪Sum= 1020‬‬
‫نالحظ انه تم التعامل مع المدخالت على انها من نوع نص ‪,‬‬
‫لذلك تم دمج القميتين الى جنب بعض ولم يقوم بجمعهم‬
‫كعددين ‪ ,‬وذلك النه في بايثون اي شي يتم ادخاله يكون‬
‫نوعه نص ‪ string‬حتى وان تم ادخال اعداد فيستم التعامل‬
‫معها على انها نص وليس عدد‪.‬‬
‫هنا نوع ‪ mark1,mark2‬نص وليس عدد‬
‫))"‪mark1 = int(input("Enter Mark1:‬‬ ‫‪Enter Mark1:‬‬
‫))"‪mark2 = int(input("Enter Mark2:‬‬ ‫‪10‬‬
‫‪sum = mark1 + mark2‬‬ ‫‪Enter Mark2:‬‬
‫)‪print("Sum=", sum‬‬ ‫‪20‬‬
‫‪OUTPUT:‬‬
‫‪CASTING‬‬ ‫‪Sum= 30‬‬
‫نالحظ انه تم تحويل القيمة المدخلة الى رقم وبعدها‬
‫تحويل القيمة المدخلة الى ‪int‬‬ ‫سيكون نوع‬
‫كل من ‪ mark1 , mark2‬رقم ‪ int‬وذلك بسبب عملية‬
‫التحويل ‪casting‬‬
‫قيمة ال ‪ sum‬ستكون من نوع ‪ int‬وذلك بسبب‬
‫تحويل المدخالت ‪int‬‬

‫))"‪mark1 = float(input("Enter Mark1:‬‬ ‫‪Enter Mark1:‬‬


‫))"‪mark2 = float(input("Enter Mark2:‬‬ ‫‪10‬‬
‫‪sum = mark1 + mark2‬‬ ‫‪Enter Mark2:‬‬ ‫قيمة ال ‪ sum‬ستكون من‬
‫)‪print("Sum=", sum‬‬ ‫‪20‬‬ ‫نوع ‪ float‬وذلك بسبب تحويل‬
‫‪OUTPUT:‬‬ ‫القيم المدخلة الى‪float‬‬
‫‪CASTING‬‬
‫‪Sum= 30.0‬‬
‫تحويل القيمة المدخلة الى ‪float‬‬

‫))"‪mark1 = float(input("Enter Mark1:‬‬ ‫‪Enter Mark1:‬‬ ‫الخطأ بسبب عملية تحويل القيمة‬
‫))"‪mark2 = float(input("Enter Mark2:‬‬ ‫‪10‬‬ ‫المدخله الى عدد ‪ ,‬حيث انه تم‬
‫‪sum = mark1 + mark2‬‬ ‫‪Enter Mark2:‬‬ ‫ادخال نص وعند عملية التحويل‬
‫)‪print("Sum=", sum‬‬ ‫‪a‬‬
‫الى ‪ float‬وقع الخطأ حيث ال يمكن‬
‫تحويا النص الى عدد‬
‫‪OUTPUT:‬‬
‫'‪ValueError: could not convert string to float: 'a‬‬
``

Handling Errors: Input Validation ‫ التحقق من‬:‫معالجة األخطاء‬


‫صحة اإلدخال‬
It’s important to ensure that the user enters valid input. For example, if the user enters non-
numeric data when an integer or float is expected, the program will raise an error.
Example of Error Handling:
We can handle these errors using try and except blocks to ensure that the program continues
smoothly even when the user enters invalid data
‫ إذا أدخل المستخدم‬،‫ على سبيل المثال‬.‫من المهم التأكد من أن المستخدم ُيدخل بيانات صحيحة‬
‫ فسيؤدي ذلك إلى‬،)float( ‫) أو عدد عشري‬integer( ‫بيانات غير رقمية بينما ُيتوقع إدخال عدد صحيح‬
.‫حدوث خطأ في البرنامج‬
:‫مثال على معالجة األخطاء‬
‫ لضمان استمرار البرنامج بسالسة‬except ‫ و‬try ‫يمكننا التعامل مع هذه األخطاء باستخدام كتلتي‬
.‫حتى عند إدخال المستخدم بيانات غير صالحة‬
Syntax:
try:
# Code that may raise an exception ‫الكود الذي قد يحتوي على خطأ‬
except ExceptionType:
# Code to handle the exception ‫الكود الذي يتم تنفيذه عند حدوث الخطأ‬

Example:
try: Enter a number:
number = int(input("Enter a number: ")) 10
print("You entered:", number) You entered: 10
except:
print("Error: Please enter a valid number.")
try: Enter a number: ‫إذا تم إدخال نص‬
number = int(input("Enter a number: ")) x ‫غير رقمي يتم‬
print("You entered:", number) Error: Please enter a except ‫التوجه الى‬
except: valid number. ‫بدل من اعطاء خطأ‬
print("Error: Please enter a valid number.") ‫في البرنامج‬

Conditional Execution ‫الجمل الشرطية‬


``

In Python, conditional steps are used to make decisions in your code based on whether a
condition is True or False. These steps are typically implemented using if, elif, and else
statements
1. if Statement
The if statement checks if a condition is True and executes a block of code if it is.
2. elif (Else If) Statement
The elif statement is used to check multiple conditions. If the if condition is False, it checks the
elif condition(s) one by one.
3. else Statement
The else statement is executed when all preceding if and elif conditions are False.
4. Nested Conditionals
You can also nest conditional statements within each other to check more complex conditions.
Python
var = input('Enter y/Y for Yes Or Enter n/N for No: ')
Multiple Conditions (and/or):
if (var =='Y' or var =='y'):
age = int(input("Enter your age: "))
print("YOU SAID YES")
if ((age>= 8) and (age<= 12)):
• Boolean expressions ask a question and produce a Yeselif(var
or No =='N' or var =='n'):
print("YOU ARE
result which weALLOWED. WELCOME!")
use to control program flow print("YOU SAID NO")
‫في‬ ‫ والتي نستخدمها للتحكم‬،‫تطرح سؤااًل وتنتج نتيجة نعم أو ال‬
else:
else:
.‫سير البرنامج‬
print("SORRY! YOU ARE NOT ALLOWED. BYE!")
print("INVALID INPUT")
• Boolean expressions using comparison operators evaluate to
True / False or Yes / No

.‫ال‬/ ‫ خطأ أو نعم‬/ ‫عوامل المقارنة ُتقّيم إلى صحيح‬

• Comparison operators look at variables but do not change


the variables

.‫عوامل المقارنة تنظر إلى المتغيرات ولكنها ال تغّير المتغيرات‬

Example:
CODE OUTPUT
age = 20 You are an adult.
if age >= 18:
print("You are an adult.")
age = 20
if age >= 30:
``

print("You are an adult.")


age = 16 You are a teenager.
if age >= 18:
print("You are an adult.")
else:
print("You are a teenager.")
age = 16 You are a child.
if age >= 18:
print("You are an adult.")
elif age >= 13:
print("You are a teenager.")
x=5 Less than 6
if x < 6 : print('Less than 6')
x=4 Not equal 6
if x != 6 :
print('Not equal 6')

One-Way Decisions

x=5 Before 5 ‫سيتم تنفيذهم‬


print('Before 5') Is 5 ‫فقط في حال تم‬
if x == 5 : Is Still 5 ‫تحقق الشرط‬
print('Is 5') Third 5
print('Is Still 5')
Afterwards 5
print('Third 5')
Before 6
print('Afterwards 5') ‫سيتم تنفيذهم‬
print('Before 6') ‫بغض النظر عن‬
‫ النهم خارج‬if ‫ال‬
if ‫نطاق ال‬

age = 18 Adult
status = "Adult" if age >= 18 else
"Minor"
print(status)
Nested Decisions
``

x = 42 More than one

if x > 1 : Less than 100


All done
print('More than one')

if x < 100 :

print('Less than 100')

print('All done')

Two-way Decisions
x=4 Bigger

if x > 2 : All done

print('Bigger')

else :

print('Smaller')

print('All done')

Multi-way
``

x=8
if x < 2 :
print('small')
Medium
elif x < 10 :
print('Medium')
else : All done
print('LARGE')
print('All done')

Multi-way Puzzles
Which will never print regardless of the value for x?
x=2
if x < 2 :
print('Below 2') Two or more
elif x >= 2 :
print('Two or more')
else :
print('Something else')

Functions
 Definition: Functions are reusable blocks of code designed to perform a specific task.
.‫الدوال هي كتل قابلة إلعادة االستخدام من التعليمات البرمجية مصممة ألداء مهمة محددة‬
``

 A function is some stored code that we use. A function takes some input and produces
an output.
‫ تأخذ الدالة مدخالت وتنتج‬.‫الدالة هي بعض التعليمات البرمجية المخزنة التي نستخدمها‬
‫مخرجات‬
 Types of Functions:
1. Built-in Functions: Provided by Python (e.g., print(), input(), max(), int(), float()).
2. User-defined Functions: Created by the programmer for specific tasks.

Function Name
Creating Functions
Parameter
 Use the def keyword to define a function.
Variables defined in
Syntax:
the function's header
def function_name(parameters): to handle arguments.

# code block(body of the function) A parameter is a


variable which we use
return result )‫القيم التي يعيدها(يحسبها‬ in the function
definition. It is a
“handle” that allows
the code in the
Optional ‫اختياري‬ function to access the
Result‫النتيجة التي تعيدها الداله‬ arguments for a
Why Use Functions? ‫لماذا نستخدم الدوال‬ particular function
invocation.
 Simplify and organize code.‫تسهيل وتنظيم الكود‬
 Reduce repetition by reusing code.‫تقليل من اعاده استخدام الكود‬
 Make programs easier to debug and maintain.‫جعل البرنامج اسهل للتتبع والتعديل‬
def thing(): Hello
print('Hello') Fun
print('Fun') Zip
thing() Hello
print('Zip') Fun
thing()

def my1(a, b): 5


``

return a+b 12
print(my1(3,2))
print(my1(my1(2,3),7))
def print_my1(): A.
print("A.") B.
print('B.')

print_my1()
print('Hello') Hello ‫لم يتم استدعاء الدالة لذلك ال‬
def print_my1(): C ‫يتم تنفيذ ما بداخلها‬
print("A.")
print('B.')
print('C')
x=5 Hello
print('Hello') Yo
def print_my1(): 7
print("A.")
print('B.')
print('Yo')
x=x+2
print(x)
def print_my1(a,b): TypeError: print_my1() ‫يجب ارسال قيميتين للدالة عند‬
return a+b; missing 1 required ‫استخدامها‬
print_my1(3) positional argument: 'b'

def greet(lang): Hello


if lang == 'es': Hola
print('Hola') Bonjour
elif lang == 'fr':
print('Bonjour')
else:
print('Hello')
greet('en')
greet('es')
greet('fr')

def greet(): Hello Glenn


return "Hello" Hello Sally
Hello Hello
print(greet(), "Glenn")
print(greet(), "Sally")
print(greet(), greet())
``

• Once we have defined a function, we can call (or invoke) it


as many times as we like ‫ يمكننا استدعاؤها (أو تنفيذها) عدد‬،‫بمجرد أن نقوم بتعريف دالة‬
‫المرات التي نريدها‬
• This is the store and reuse pattern ‫هذا هو نمط التخزين وإعادة االستخدام‬.

Void (non-fruitful) Functions:


• When a function does not return a value, we call it a “void” function
"‫ ُنسميها دالة "فارغة‬،‫عندما ال ُترجع الدالة قيمة‬
• Functions that return values are “fruitful” functions ‫الدوال التي ُترجع قيًما ُتسمى دوال‬
‫مثمرة‬
• Void functions are “not fruitful” ‫الدوال الفارغة غير مثمرة‬

Recursion Functions
that calls itself is known as a recursive function. And the process is known as recursion.
‫ وُتعرف العملية بالتكرار‬،‫الدالة التي تستدعي نفسها بالدالة التكرارية‬

The recurse() function calls itself over and over again.

def greet(): Hello


print('Hello')
# recursive call Hello
greet() Hello
# normal function call .
greet() .
``

Stopping Condition for Recursion:


If we do not include a stopping condition to stop the recursive call, the function will keep calling
itself infinitely. We generally use the if...else statement to stop the recursion.
‫ فإن الدالة ستستمر في استدعاء نفسها بشكل غير‬،‫إذا لم ُندِرج شرًطا إليقاف االستدعاء التكراري‬
.‫ إليقاف التكرار‬if...else ‫ عادًة ما نستخدم جملة‬.‫محدود‬
def print_number(number):
# print number
Output:
print(number)
2
# stopping condition
1
if number == 0: ‫شرط التوقف‬
0
print('Stop Printing')
Stop Printing
else:
# recursive call
print_number(number - 1) ‫استدعاء الدالة مع طرح وحد من الرقم‬

print_number(2)

Python recursive function to calculate the sum of natural numbers


def sum_of_natural_numbers(n):
# Base condition: if n is 1, return 1
OUTPUT:
if n == 1:
The sum of the first 5 natural numbers is: 15
return 1
else:
# Recursive call: add n to the sum of natural numbers up to n-1
return n + sum_of_natural_numbers(n - 1)

# Example usage:
``

n=5
result = sum_of_natural_numbers(n)
print(f"The sum of the first {n} natural numbers is: {result}")

Python Recursive Function to Find Odd Numbers:


def print_odd_numbers(n, current=1):
# Base case: If current exceeds n, stop recursion
if current > n: OUTPUT:
return 1
# Print the current number if it is odd 3
if current % 2 != 0: 5
print(current) 7
# Recursive case: Call the function for the next number 9
print_odd_numbers(n, current + 2)

# Example usage
print_odd_numbers(10)

Loops
Loops are used to perform repetitive tasks efficiently. Python provides two main types of loops:
1. while loop: Runs as long as a condition is True.
2. for loop: Iterates over a sequence or set.
While Loops
Definition: Executes the block of code repeatedly as long as the condition is True.
Loops (repeated steps) have iteration variables that change each time through a loop. Often these
iteration variables go through a sequence of numbers
.‫الحلقات (الخطوات المتكررة) تحتوي على متغيرات تكرار تتغير في كل مرة تمر فيها عبر الحلقة‬
.‫غالًبا ما تمر هذه المتغيرات عبر تسلسل من األرقام‬
Code Output
``

n=5 5
while n > 0: 4
print(n) 3
n=n-1 2
print("Blastoff!") 1
Blastoff!

while True: infinite loop ‫تكرار النهائي‬


print("This is an infinite loop")
n=5 infinite loop ‫تكرار النهائي‬
while n > 0 : ‫ ال تتغير وتظل ثابتة‬n ‫الن قيمة‬
print('Lather')
print('Rinse')
print('Dry off!')
x=1 2
while x<=5: 3
x +=1 4
print(x) 5
print('Done!') 6
Done!
x=1 1
while x<=5: 2
print(x) 3
x +=1 4
print('Done!') 5
Done!

for i in [5, 4, 3, 2, 1]: 5


print(i) 4
print("Blastoff!") 3
2
1
Blastoff!
largest_so_far = -1 Before: -1
print("Before:", largest_so_far) After: 74
for num in [9, 41, 12, 3, 74, 15]:
if num > largest_so_far:
largest_so_far = num
print("After:", largest_so_far)
smallest = None Before: None
print("Before:", smallest) After: 3
for num in [9, 41, 12, 3, 74, 15]:
if smallest is None or num < smallest:
smallest = num
``

print("After:", smallest)
count = 0 Count: 6
for num in [9, 41, 12, 3, 74, 15]:
count += 1
print("Count:", count)
count = 0 Avg: 25.666666666666668
sum = 0
avg= 0.0
for num in [9, 41, 12, 3, 74, 15]:
count += 1
sum = sum + num

avg = sum/count
print("Avg:", avg)
2
x=1 3
while True: 4
if x == 5: 5
break Done!
x +=1
print(x) ‫تستخدم‬
print('Done!') break
‫النهاء‬
‫التكرار‬

x=1 1
while True: 3
if x == 2 : 4
x+=1 Done!
if x == 5:
break
print(x)
x = x+1
print('Done!')
for x in [3,2,4,5,6]: 3
if x == 2 : 4
continue Done!
if x == 5: loop ‫ بالعوده الى ال‬continue ‫تقوم‬
break
print(x)
print('Done!')
``





















‫متغير التكرار "يتكرر" عبر التسلسل (مجموعة‬
.)‫مرتبة‬
‫يتم تنفيذ كتلة (جسم) التعليمات البرمجية‬ •
.‫مرة واحدة لكل قيمة في التسلسل‬
‫• يتحرك متغير التكرار عبر جميع القيم في‬
.‫التسلسل‬

Indefinite Loops Definite Loops Loop Idioms


• While loops are called • Quite often we have a What We Do in Loops
“indefinite loops” list of items of the lines
because they keep going in a file - effectively a
until a logical condition finite set of things
becomes False • We can write a loop to
• The loops we have seen run the loop once for
so far are pretty easy to each of the items in a set
examine to see if they using the Python for
will terminate or if they construct
will be “infinite loops” • These loops are called
• Sometimes it is a little “definite loops” because
harder to be sure if a loop they execute an exact
will terminate number of times
• We say that “definite
loops iterate through the
``

members of a set”

Range in Python -- range(start, stop, step)


In Python, the range() function is commonly used to generate a sequence of numbers. It's
especially useful in loops, particularly for loops.
.‫تستخدم لتوليد تسلسل من األرقام‬

Examples:
Code Output
for i in range(5): 0
print(i) 1
2
3
4
for i in range(2, 6): 2
print(i) 3
4
5
for i in range(1, 10, 2): 1
print(i) 3
5
7
9

for i in range(10, 0, -2): 10


print(i) 8
6
4
2
for i in range(10): 1
if i % 2 == 0: # Skip even numbers 3
continue 5
print(i) 7
9
for i in range(5): range(0, 0)
print(range(i)) range(0, 1)
range(0, 2)
range(0, 3)
range(0, 4)
``

Strings
Definition: A string is a sequence of characters.
String literals: Use single ('Hello') or double quotes ("Hello").
Concatenation: Using the + operator to join strings.
Example: 'Hello ' + 'World' → Hello World
Numbers as Strings: Numbers in a string format can be converted using int() or float().
String Function:
upper sentence = "Python" The upper() )(upper ‫دالة‬
uppercase_sentence = sentence.upper() function is useful ‫تستخدم لتحويل‬
print(uppercase_sentence) # Output: PYTHON when you need to ‫السلسلة النصية‬
make a string ‫إلى أحرف كبيرة‬
fully uppercase ‫بالكامل‬
lower sentence = "Python" The lower() ‫تستخدم لتحويل‬
new_sentence = sentence.lower() function is used to ‫السلسلة النصية‬
print(uppercase_ sentence) # Output: python convert all ‫إلى أحرف‬
characters in a ‫صغيرة بالكامل‬
string to
lowercase.
len text = "Hello, world!" Used to return the ‫إلرجاع عدد‬
length = len(text) number of items )‫العناصر (الطول‬
print(length) # Output: 13 (length) in an ‫في كائن مثل‬
object such as a ،‫السلسلة النصية‬
string, list, tuple, ،‫ الطقم‬،‫القائمة‬
dictionary, or ‫ أو أي‬،‫القاموس‬
other iterable. ‫كائن قابل‬
.‫للتكرار آخر‬
replace string.replace(old, new, count) Replace parts of a ‫ُتستخدم‬
string with ‫الستبدال‬
text = "Hello, world!" another substring. ‫أجزاء من‬
new_text = text.replace("world", "Python") This method does ‫السلسلة‬
print(new_text) # Output: Hello, Python! not modify the ‫النصية‬
original string ‫بسلسلة نصية‬
text = "apple apple apple" (because strings ‫ال تقوم‬. ‫أخرى‬
new_text = text.replace("apple", "orange", 2) are immutable in ‫هذه الطريقة‬
print(new_text) # Output: orange orange apple Python) but ‫بتعديل‬
returns a new ‫السلسلة‬
string with the ‫النصية‬
specified ‫األصلية (ألن‬
replacements. ‫السالسل‬
‫النصية غير‬
‫قابلة للتغيير‬
``

)‫في بايثون‬
‫بل ُترجع‬
‫سلسلة نصية‬
‫جديدة تحتوي‬
‫على التعديالت‬
‫المحددة‬
find text = "Hello, world!" used to search for ‫ُتستخدم للبحث‬
index = text.find("world") a substring within ‫عن جزء من‬
print(index) # Output: 7 a string. It returns ‫النص داخل‬
the lowest index .‫سلسلة نصية‬
text = "Hello, world!" where the ‫ُترجع أقل فهرس‬
index = text.find("Python") substring is found ‫يتم العثور فيه‬
print(index) # Output: -1 or -1 if the ‫على الجزء‬
substring is not ‫ إذا‬1- ‫ أو‬،‫الفرعي‬
data = 'From [email protected]' found. ‫لم يتم العثور‬
atpos = data.find('@') ‫على الجزء‬
print(atpos) # Output: 21 .‫الفرعي‬

data = 'From [email protected]'


atpos = data.find('@')
sppos = data.find(' ',atpos)
host = data[atpos+1 : sppos]
print(host) # Output: uct.ac.z

lstrip greet = ' Hello Bob ' Remove ‫حذف الفراغات‬


greet.lstrip() whitespace at the ‫من جهة اليسار‬
Output 'Hello Bob ' left
rstrip greet = ' Hello Bob ' Remove ‫حذف الفراغات‬
greet.rstrip() whitespace at the ‫من جهة اليمين‬
Output ' Hello Bob' right
x = ' Hello ' Hello Word
y= 'Word'
print(x.lstrip(), end='')
print(y)
x = ' Hello ' HelloWord
y= 'Word'
print(x.lstrip().rstrip(), end='')
print(y)

x = ' Hello ' HelloWord


y= ' Word '
print(x.lstrip().rstrip(), end='')
print(y.lstrip())

startswith text = "Hello, world!" Used to check if a ‫ُتستخدم للتحقق‬


result = text.startswith("Hello") string starts with a ‫مما إذا كانت‬
``

print(result) # Output: True specified prefix. It ‫السلسلة النصية‬


returns True if the ‫تبدأ بالبادئة‬
text = "Hello, world!" string begins with ‫ ُترجع‬.‫المحددة‬
result = text.startswith("Python") the given prefix, ‫ إذا كانت‬True
print(result) # Output: False and False ‫السلسلة تبدأ‬
otherwise. ،‫بالبادئة المعطاة‬
text = "Hello" ‫ في حال‬False ‫و‬
result = text.startswith("h") .‫كانت ال تبدأ بها‬
print(result) # Output: False

text = "Hello, world!"


result = text.startswith("world", 7) print(result)
# Output: True (since "world" starts at index 7)

split text = "Hello, world! Welcome to Python." used to divide a ‫ُتستخدم لتقسيم‬
result = text.split() string into a list of ‫السلسلة النصية‬
print(result) substrings based ‫إلى قائمة من‬
# Output: ['Hello,', 'world!', 'Welcome', 'to', on a specified ‫األجزاء الفرعية‬
'Python.'] delimiter ‫بناًء على فاصل‬
(separator). By .)‫محدد (فاصل‬
text = "apple,orange,banana,grapes" default, it splits ،‫بشكل افتراضي‬
result = text.split(",") the string at any ‫تقوم بتقسيم‬
print(result) whitespace ‫السلسلة النصية‬
# Output: ['apple', 'orange', 'banana', 'grapes'] (spaces, newlines, ‫عند أي مسافة‬
tabs). ‫فارغة‬
text = "apple orange banana grapes" ،‫(المسافات‬
result = text.split(" ", 2) ،‫األسطر الجديدة‬
print(result) .)‫التبويبات‬
# Output: ['apple', 'orange', 'banana grapes']
capitalize text = "hello world" Changes the first ‫يغير الحرف‬
title_text = text.title() character of the ‫األول من‬
string to ‫السلسلة إلى‬
print(title_text) # Output: Hello World uppercase, while ( ‫حرف كبير‬
the rest of the ‫ بينما‬،)uppercase
string becomes ‫يصبح باقي‬
lowercase. ‫السلسلة أحرًفا‬
( ‫صغيرة‬
.)lowercase

EXAMPLE:

Code Output
``

fruit = 'banana' 'banana'


print(fruit)
fruit = 'banana' a
print(fruit[1])
fruit = 'banana' n
print(fruit[4])
fruit = 'banana' Traceback (most recent call last):
print(fruit[9]) File "main.py", line 2, in <module>
print(fruit[9])
IndexError: string index out of range
First = ‘Ali’ AliKhaled
Last = ‘Khaled’
Full = First + Last
print(Full)

First = 'Ali' Ali Khaled


Last = 'Khaled'
Full = First + ' ' + Last
print(Full)
fruit = 'banana' TypeError: 'str' object does not support item
fruit[1] ='x' assignment
‫ال يمكن تعديل اي حرف داخل النص باستخدام‬
index
word = 'banana' 3
count = 0 ‫ داخل نص‬a ‫لحساب عدد احرف‬
for letter in word :
if letter == 'a' :
count = count + 1
print(count)
name = 'Ali' TypeError: can only concatenate str (not
mark = 40 "int") to str
Full = name + ' ' + mark ‫ال يمكن جمع مص مع رقم‬
print(Full)
name = 'Ali' Ali 40
mark = 40
Full = name + ' ' + str(mark)
print(Full)
word = 'Banana' Your word,Banana, comes before banana.
if word == 'banana':
print('All right, bananas.')

if word < 'banana':


print('Your word,' + word + ', comes before
``

banana.')
elif word > 'banana':
print('Your word,' + word + ', comes after
banana.')
else:
print('All right, bananas.')
word = 'Banana' Banana
x= word.lower() ‫() لتحويل احرف‬lower ‫تستخدم الدالة‬
print(x) ‫النص ال احرف صغيرة‬
word = 'Banana' BANANA
x= word.upper() ‫() لتحويل احرف‬upper ‫تستخدم الدالة‬
print(x) ‫النص ال احرف كبيره‬
word = 'Banana' 6
x= len(word) ‫() اليجاد طول عدد‬len ‫تستخدم الدالة‬
print(x) ‫احرف النص‬
print('Hi There'.lower()) hi there
print('Hi There'.upper()) HI THERE

text = "Hello, world!" Hello, Python!


new_text = text.replace("world", "Python") replace()
print(new_text) .

Slicing:
In Python, string slicing allows you to extract a portion (substring) of a string by specifying a
range of indices.
string[start:stop:step]
start: The index to start the slice (inclusive). Defaults to 0 if omitted.
stop: The index to end the slice (exclusive).
step: The step (interval) between characters. Defaults to 1.
Code Output
text = "Hello, World!" Hello
print(text[0:5]) # Extracts characters from index 0 to 4
text = "Hello, World!" Hello
print(text[:5]) # From the start to index 4 World!
print(text[7:]) # From index 7 to the end
text = "Hello, World!" World!
print(text[-6:]) # Last 6 characters ‫ احرف من النص‬6 ‫طباعه اخر‬
text = "Python is fun!" is
substring = text[7:9]
print(substring)
``

Length of Strings
len() function: Returns the number of characters in a string
Code Output
print(len('banana')) 6
fruit = 'banana' b
index = 0 a
while index < len(fruit): n
print(fruit[index]) a
index += 1 n
a

for letter in 'banana': b


print(letter) a
n
a
n
a

word = 'Banana' It's not banana!


if word != 'banana':
print('It\'s not banana!')
print('n' in 'banana') True
``

Exercises
Exercise1
Write a program that iterates through the list [1, 4, 7, 2, -1, -5]
using a for loop to find the negative numbers.
ANSWER:
# Loop through the list to find negative numbers
negative_numbers = []
for num in [1, 4, 7, 2, -1, -5]:
if num < 0:
negative_numbers.append(num)
# Print the list of negative numbers
print("Negative numbers:", negative_numbers)
Exercise2
Write a python program that defines a function circular to calculate the area of three balloon
wheels (circular) based on user input for their radius. The function will use a loop to get each
radius, calculate the area, and print the area of the largest wheel.
Note: The area of the current wheel is calculated using the formula πr^2 (math.pi * radius**2).
ANSWER:
import math

def circular():
largest_area = 0 # Initialize the largest area to 0

# Loop to get the radius and calculate the area of three wheels
for i in range(1, 4):
radius = float(input("Enter the radius of balloon wheel: "))
area = math.pi * radius**2 # Formula for the area of a circle: πr^2
print("The area of balloon wheel is:”, area)

# Update the largest_area if the current area is larger


if area > largest_area:
largest_area = area

# Print the area of the largest wheel


print("The area of the largest wheel is: ", largest_area)

# Call the circular function


circular()
``

Exercise3
Write a python program that provides a menu to calculate the area of a square, triangle, and
circle. It also includes an "Exit" option in the menu. If the user enters a value that is not part of
the menu options, the program keeps giving them another chance until a valid option is selected.

ANSWER:
import math
# Function to calculate the area of a square
def square_area():
side = float(input("Enter the side length of the square: "))
area = side ** 2
print(f"The area of the square is: {area:.2f}")
# Function to calculate the area of a triangle
def triangle_area():
base = float(input("Enter the base length of the triangle: "))
height = float(input("Enter the height of the triangle: "))
area = 0.5 * base * height
print(f"The area of the triangle is: {area:.2f}")
# Function to calculate the area of a circle
def circle_area():
radius = float(input("Enter the radius of the circle: "))
area = math.pi * radius ** 2
print(f"The area of the circle is: {area:.2f}")
``

# Main method that presents the menu and handles user input
while True:
print("\nMenu:")
print("1. Calculate area of a square")
print("2. Calculate area of a triangle")
print("3. Calculate area of a circle")
print("4. Exit")

# Get user input


choice = input("Enter your choice (1-4): ")

# Process user input


if choice == '1':
square_area()
elif choice == '2':
triangle_area()
elif choice == '3':
circle_area()
elif choice == '4':
print("Exiting the program. Goodbye!")
break # Exit the loop and end the program
else:
print("Invalid choice. Please enter a number between 1 and 4.")
``

Exercise4
Program that checks the agreement of the user to the terms

ANSWER:
a=int(input("Enter the first number:"))
b=int(input"Enter the second number:"))
c=int(input("Enter the third number:"))
if((a>b and a>c) and (a != b and a != c)):
print(a, " is the largest")
elif((b>a and b>c) and (b != a and b != c)):
print(b, " is the largest")
elif((c>a and c>b) and (c != a and c != b)):
print(c, " is the largest")
else:
print("entered numbers are equal")
``

Exercise5
"""Technology is revolutionizing our world at an unprecedented pace. From artificial intelligence
to blockchain, and from self-driving cars to quantum computing, the innovations of today will
reshape the societies of tomorrow. While these technologies promise greater efficiency and
convenience, they also raise ethical concerns. Will robots replace humans in jobs? Will data
privacy become obsolete as surveillance grows? As we stand on the edge of this technological
transformation, it is essential to consider both the opportunities and the challenges that lie
ahead."""

Providing a text read it then answer the following questions based on text. And print each output
separately:
1. Extracts the word "revolutionizing"
2. Get the first 30 characters of the text
3. Check if the word "robots" is present
4. Check if "blockchain" is in text
5. What is the largest word between "convenience" and " consider"
6. Capitalize first letter in "robots are taking over "
7. Replace "robots" with "machines“
8. Convert entire text to lowercase
9. Remove trailing whitespaces in " Technology is amazing! "
10. Remove both leading and trailing whitespaces " The future is near! "
11. Check if text starts with "Technology“
12. Convert entire text to uppercase
13. Check if text ends with "ahead.“
14. Find position of "quantum" in the text
15. Find "data" starting from index 50
16. Split text by period ‫ النقطة‬into sentences
17. Split by commas "Innovation, progress, change "
``

ANSWER:
# Provided text
text = "Technology is revolutionizing our world at an unprecedented pace. From artificial
intelligence to blockchain, and from self-driving cars to quantum computing, the
innovations of today will reshape the societies of tomorrow. While these technologies
promise greater efficiency and convenience, they also raise ethical concerns. Will robots
replace humans in jobs? Will data privacy become obsolete as surveillance grows? As we
stand on the edge of this technological transformation, it is essential to consider both the
opportunities and the challenges that lie ahead."

# 1. Extract the word "revolutionizing"


revolutionizing = text.split()[0]
print("Extracted word:", revolutionizing)

# 2. Get the first 30 characters of the text


first_30_chars = text[:30]
print("First 30 characters:", first_30_chars)

# 3. Check if the word "robots" is present


robots_present = "robots" in text
print("Is 'robots' present:", robots_present)

# 4. Check if "blockchain" is in text


blockchain_present = "blockchain" in text
print("Is 'blockchain' present:", blockchain_present)

# 5. What is the largest word between "convenience" and "consider"


if 'convenience' > 'consider':
print('convenience>consider')
else:
print('consider>convenience')

# 6. Capitalize first letter in "robots are taking over "


sentence = "robots are taking over"
capitalized_sentence = sentence.capitalize()
print("Capitalized sentence:", capitalized_sentence)

# 7. Replace "robots" with "machines"


replaced_text = text.replace("robots", "machines")
print(replaced_text)

# 8. Convert entire text to lowercase


lowercase_text = text.lower()
``

print("Lowercase text:", lowercase_text)

# 9. Remove trailing whitespaces in " Technology is amazing! "


trailing_whitespaces_removed = " Technology is amazing! ".rstrip()
print("Text with trailing whitespaces removed:", trailing_whitespaces_removed)

# 10. Remove both leading and trailing whitespaces " The future is near! "
leading_trailing_removed = " The future is near! ".strip()
print("Text with leading and trailing whitespaces removed:", leading_trailing_removed)

# 11. Check if text starts with "Technology"


starts_with_technology = text.startswith("Technology")
print("Does the text start with 'Technology'? :", starts_with_technology)

# 12. Convert entire text to uppercase


uppercase_text = text.upper()
print("Uppercase text:", uppercase_text)

# 13. Check if text ends with "ahead."


ends_with_ahead = text.endswith("ahead.")
print("Does the text end with 'ahead.'? :", ends_with_ahead)

# 14. Find position of "quantum" in the text


quantum_position = text.find("quantum")
print("Position of 'quantum' in the text:", quantum_position)

# 15. Find "data" starting from index 50


data_position = text.find("data", 50)
print("Position of 'data' starting from index 50:", data_position)

# 16. Split text by period into sentences


sentences = text.split(".")
print("Sentences after splitting by period:", sentences)

# 17. Split by commas


comma_split = "Innovation, progress, change ".split(",")
print("Text after splitting by commas:", comma_split)
``

Exercise5
Write a python code to calculate a BMI((Body Mass Index)

Answer:
# Input for height and cast to a float
height = float(input("Enter your height in meters: "))
# Input for weight and cast to a float
weight = float(input("Enter your weight in kg: "))
# Calculate BMI
bmi = weight / (height ** 2)
# Output the results
print(f"Hello {name}, you are {age} years old.")
print("Your BMI is: “,bmi)

Exercise6
Rewrite your pay computation(BMI) using a function.

Answer
# Function to calculate BMI
def calculate_bmi(weight, height):
# BMI formula
bmi = weight / (height ** 2)
return bmi

# Input: weight in kilograms and height in meters


weight = float(input("Enter your weight in kilograms: "))
height = float(input("Enter your height in meters: "))
``

# Calculate BMI
bmi = calculate_bmi(weight, height)

# Output the BMI value


print("Your Body Mass Index (BMI) is: “,bmi")

Exercise7
Rewrite your pay computation(BMI) using a function with using try and except

Answer
# Function to calculate BMI
def calculate_bmi(weight, height):
# BMI formula
bmi = weight / (height ** 2)
return bmi

# Input: weight in kilograms and height in meters


try:
weight = float(input("Enter your weight in kilograms: "))
height = float(input("Enter your height in meters: "))
except:
print("Invalid Input")

# Calculate BMI
bmi = calculate_bmi(weight, height)

# Output the BMI value


print("Your Body Mass Index (BMI) is:", bmi)
``

Exercise8
Write a program to enter a student's grades in the last semester:
Noah Smith (ID: 2023100099)
Programming 1 (3 credit hours) 85
Lab Programming 1 (1 credit hour) 80
Calculus (3 credit hours) 65
English 1 (3 credit hours) 70
Intro to Information Technology (3 credit hours) 82

Find the followin:


 Try to make your output match the required format.
 Include the number of credit hours.
 Use an appropriate number of spaces, \n, or \t.
 Use appropriate data types for writing the program.
 Use the appropriate format for printing the average.
Answer
print("Welcome to \"Zarqa University\"")
print("Department of Artificial Intelligence\n")

# Gather student information


first_name = input("Please, Enter your given first name: ")
last_name = input("Please, Enter your given last name: ")
student_id = input("Please, Enter your ID: ")

# Gather grades for each course


course_1_grade = int(input("Please, Enter your grade in Programming 1 : "))
course_2_grade = int(input("Please, Enter your grade in Lab Programming 1 : "))
course_3_grade = int(input("Please, Enter your grade in Calculus : "))
``

course_4_grade = int(input("Please, Enter your grade in English 1 : "))


course_5_grade = int(input("Please, Enter your grade in Intro to Information Technology : "))

# Calculate total grades


total_grades = (
course_1_grade + course_2_grade + course_3_grade + course_4_grade + course_5_grade
)

# Calculate average
gpa = total_grades / 5

# Output the result


print(f"{first_name} {last_name} ( {student_id} ) Your Average")
print(gpa)
print("Thank you")

Exercise9
Write a Python program that takes three grades as input from the user and determines the highest
grade. The program should then print out a message stating which grade is the highest.
Answer
# Take input for three grades
grade1 = float(input("Enter grade 1: "))
grade2 = float(input("Enter grade 2: "))
grade3 = float(input("Enter grade 3: "))
``

# Determine the highest grade manually


if grade1 >= grade2 and grade1 >= grade3:
highest_grade = grade1
elif grade2 >= grade1 and grade2 >= grade3:
highest_grade = grade2
else:
highest_grade = grade3

# Print the result


print("The highest grade is ", highest_grade)

Exercise10
Write a python code to calculate an employee's salary with tax applied, then find tax amount
and net salary and basic salary.
Answer
# Input the employee's basic salary
basic_salary = float(input("Enter the employee's basic salary: "))

# Input the tax rate (as a percentage)


tax_rate = float(input("Enter the tax rate : "))

# Calculate the tax amount


tax = (tax_rate / 100) * basic_salary

# Calculate the net salary


net_salary = basic_salary - tax

# Display the results


print("Salary Details :")
``

print("Basic Salary: ",basic_salary)


print(f"Tax Amount: " tax)
print("Net Salary: " net_salary)

Exercise11
Write a Python program to calculate the total parking amount for a vehicle based on the
following conditions:
The user inputs the number of hours the vehicle was parked (hours_parked) and the hourly rate
(rate_per_hour).
If the total hours parked are 24 or fewer:
Calculate the parking amount as hours_parked * rate_per_hour.
Ensure that the amount does not exceed a maximum daily charge of 50.0 JOD.
If the total hours parked exceed 24:
Calculate the cost for full days (using the maximum daily charge for each full day).
Add the cost for the remaining hours, ensuring that it does not exceed the daily maximum.
The program should display:
The number of hours parked.
The total parking amount in Jordanian Dinars (JOD).
Output(As Example):
--- Parking Details ---
Hours Parked: 30.0
Parking Amount: 55.0 JOD
``

Answer
# Input the number of hours the vehicle was parked
hours_parked = float(input("Enter the number of hours parked: "))
rate_per_hour = float(input("Enter the rate per_hour: "))

# Define maximum daily charge


max_daily_charge = 50.0

# Calculate the total parking amount


if hours_parked <= 24:
parking_amount = min(hours_parked * rate_per_hour, max_daily_charge)
else:
# Calculate for days and remaining hours if parking exceeds 24 hours
full_days = int(hours_parked // 24)
remaining_hours = hours_parked % 24
parking_amount = (full_days * max_daily_charge) + min(remaining_hours * rate_per_hour,
max_daily_charge)

# Display the parking amount


print("\n--- Parking Details ---")
print(f"Hours Parked: ", hours_parked)
print(f"Parking Amount:" , str(parking_amount) + str("JOD"))
``

Exercise12
Python function that prompts the user to input their first and last name (in a single input without
spaces) and calculates the maximum and minimum letters
Example
Input:
AdamMichele
Output:
''Maximum letter is:'' m
''Minimum letter is:'' A
Answer
def max_min_letters():
# Prompt the user to enter their first and last name (without spaces)
name = input("Enter your first and last name (without spaces):
# Calculate the maximum and minimum letters
max_letter = max(name)
min_letter = min(name)

# Display the results


print("Maximum letter:", max_letter)
print("Minimum letter:", min_letter)

# Call the function


max_min_letters()
``

Exercise13
Write a function named car, it has two parameters Type and Year will be entered by the user. It
checks:
-if the Model is "Electronic" and then the Year is greater than 2014 print "Tax is 30%",
otherwise, print "No Tax"
-if the Model is "Hybrid" and then the Year is greater than 2014 print "Tax is 20%", otherwise,
print "No Tax"
-if the Model is "petrol" and then the Year is greater than 2014 print "Tax is 0%", otherwise,
print "No Tax"
otherwise, print "Wrong Entry"

Answer
def car(Type, Year):
# Convert user input to lowercase for case-insensitive comparison
Type = Type.lower()

# Check conditions based on Type and Year


if Type == "electronic":
if Year > 2014:
print("Tax is 30%")
else:
print("No Tax")
elif Type == "hybrid":
if Year > 2014:
print("Tax is 20%")
else:
print("No Tax")
elif Type == "petrol":
if Year > 2014:
print("Tax is 0%")
``

else:
print("No Tax")
else:
print("Wrong Entry")

# Get user input for car type and year


car_type = input("Enter the car type (Electronic, Hybrid, Petrol): ")
car_year = int(input("Enter the manufacturing year: "))

# Call the function with user input


car(car_type, car_year)

Exercise14
Write a python function to calculates the Fibonacci number using recursion.

Answer
def fibonacci(n):
# Base case: return n if it's 0 or 1
if n <= 1:
return n
else:
# Recursive call: sum of the previous two Fibonacci numbers
return fibonacci(n - 1) + fibonacci(n - 2)

# Example usage
result = fibonacci(5)
print(result) # Output: 5 (The 5th Fibonacci number is 5)
``

Exercise15
Write a python code to reverses a string using recursion.

Answer
def reverse_string(s):
# Base case: if string is empty or has one character, return it
if len(s) == 0:
return s
else:
# Recursive call: reverse the rest of the string and add the first character at the end
return reverse_string(s[1:]) + s[0]

# Example usage
result = reverse_string("hello")
print(result) # Output: "olleh"

Exercise16
Write a python code to Find the Greatest Common Divisor (GCD)

Answer
def gcd(a, b):
# Base case: if b is 0, return a as the GCD
if b == 0:
return a
else:
# Recursive case: find GCD of b and a % b
return gcd(b, a % b)
# Example usage
result = gcd(56, 98)
print(result) # Output: 14
``

Exercise17
Write a python code to prints numbers from n down to 1 using recursion.

Answer
def countdown(n):
# Base case: if n is 0, stop recursion
if n == 0:
print("Done!")
return
else:
print(n)
# Recursive call: countdown with n-1
countdown(n - 1)

# Example usage
countdown(5)

Exercise17
Write a python code to find x raised to the power of y recursively (x^y) using recursion.

Answer
def power(x, y):
if y == 0:
return 1
else:
return x * power(x, y - 1)

# Example
print(power(2, 3)) # Output: 8
``

Exercise18
Write a python code to displays a half pyramid pattern (right side)
*
**
***
****

Answer
base_size = int(input("Enter number lines for triangle patter: "))
for r in range(base_size):
for c in range(r + 1):
print('*', end='')
print()

Exercise19
Write a python code to displays a half pyramid pattern (left side)
****
***
**
*

Answer
base_size =int(input("Enter number lines for triangle patter: "))
for r in range(base_size,0,-1):
#print(r)
for c in range(r-1):
print(' ',end='')
for t in range(base_size-r+1):
print('*',end='')
print()
``

Exercise20
Write a python code to displays an inverted half pyramid pattern (left side)
****
***
**
*

Answer
base_size = int(input("Enter number lines for triangle patter: "))
for r in range(base_size,0,-1):
#print(r)
for t in range(base_size-r):
print(' ',end='')
for c in range(r):
print('*',end='')
print()

Exercise21
Write a python code to displays an inverted full pyramid pattern
*******
*****
***
*

Answer
n = int(input("Enter number of stars at the first line(Note: it should be odd number): "))
if n%2==0:
n=n+1
#print("n=", n)
for i in range(1, n+1):
# Print leading spaces
for j in range(0, i-1):
print(" ", end="")
# Print asterisks for the current row
for k in range(n - 2*(i-1)):
print("*", end="")
print()
``

Exercise22
Write a python code to displays an inverted full pyramid pattern
*
***
*****

Answer
n = int(input("Enter number of stars at the last line: "))
for i in range(1, n + 1):
# Print leading spaces
for j in range(n - i):
print(" ", end="")
# Print asterisks for the current row
for k in range(1, 2*i):
print("*", end="")
print()

Exercise23
Write a python code to displays an inverted full pyramid pattern
1
12
123
1234

Answer
n = int(input("Enter number of at the last line: "))
# Loop through the range of rows
for i in range(1, n+1):
# Print numbers from 1 to i in each row
for j in range(1, i + 1):
print(j, end="")
# Move to the next line after each row
print()
``

Test Exam 1
Multiple Choice Questions
1. What will be the output of the following Python code?
x = 10
y=5
print(x * y)
a) 10
b) 15
c) 50
d) Error
2. Which of the following is the correct way to check if a string contains the word "apple"
in Python?
a) "apple" in string
b) string.contains("apple")
c) string.include("apple")
d) "apple" == string
3. Which loop will correctly print the numbers 1 through 5?
a)
for i in range(1, 6):
print(i)
b)
for i in range(0, 5):
print(i)
c)
while i <= 5:
print(i)
d)
for i in range(1, 4):
print(i)
``

4. What is the correct syntax for defining a variable in Python?


a) variable = 10
b) int variable = 10
c) 10 = variable
d) var: 10

Output-Based Questions
5. What will be the output of the following Python code?
a = "hello"
b = "world"
print(a + b)
a) "hello world"
b) "helloworld"
c) "hello"
d) "world"
6. What will be the output of the following Python code?
number = 10
if number > 5:
print("Greater")
else:
print("Smaller")
a) "Greater"
b) "Smaller"
c) "Greater" Smaller
d) "Greater Smaller"
7. What will be the output of the following Python code?
text = "Python"
print(text[::-1])
a) "nohtyP"
b) "Python"
c) "P"
d) "onhtyP"
``

Writing Questions
8. Write a Python program that:
 Prompts the user to input their age.
 If the age is less than 18, prints: "You are a minor".
 If the age is 18 or more, prints: "You are an adult".
9. Write a Python function count_vowels that:
 Takes a string as input.
 Returns the count of vowels (a, e, i, o, u) in the string. Ignore case.
Example:
count_vowels("Hello World") # Output should be 3

Answer Key
1. c) 50
2. a) "apple" in string
3. a)
python
Copy code
for i in range(1, 6):
print(i)
4. a) variable = 10
5. b) "helloworld"
6. a) "Greater"
7. a) "nohtyP"

Solution Examples for Writing Questions


8. Age check program:
# Age check program
age = int(input("Enter your age: "))
``

if age < 18:


print("You are a minor")
else:
print("You are an adult")
9. Count vowels function:
def count_vowels(input_string):
vowels = "aeiouAEIOU"
count = 0
for char in input_string:
if char in vowels:
count += 1
return count

# Example usage:
print(count_vowels("Hello World")) # Output: 3
``

Multiple Choices EXAM

What is the correct way to declare a variable in Python?


A) x = 5 ✔
B) declare x = 5
C) variable x = 5
D) let x = 5
E) int x = 5
----------
What will be the output of the following code?
for i in range(3):
print(i)
A) 0 1 2 3
B) 1 2 3
C) 0 1 2 ✔
D) 0 1
E) 1 2
----------
Which of the following is used to start a conditional statement in Python?
A) for
B) if ✔
C) case
D) while
E) switch
``

How do you create a multiline string in Python?


A) Using single quotes (' ')
B) Using double quotes (" ")
C) Using triple single quotes (''' ''' ) ✔
D) Using backslashes (\)
E) Using parentheses ()

What is the output of the following code?


a = 'Hello'
print(a[1])
A) l
B) e ✔
C) Error
D) o
E) H
----------
Which keyword is used to exit a loop prematurely in Python?
A) break ✔
B) return
C) exit
D) stop
E) continue
``

How do you check the type of a variable `x` in Python?


A) typeof(x)
B) x.type()
C) getType(x)
D) type of x
E) type(x) ✔
----------
What will the following code print?
x = 10
if x > 5:
print('Greater')
elif x == 5:
print('Equal')
else:
print('Less')
A) Nothing
B) Less
C) Error
D) Equal
E) Greater ✔

Which of the following functions can be used to get the length of a string in Python?
A) length()
B) len() ✔
C) sizeof()
D) count()
E) size()
----------
``

What is the purpose of the `continue` statement in a loop?


A) To pause the loop
B) To exit the program
C) To terminate the loop
D) To restart the loop from the beginning
E) To skip the rest of the current loop iteration and continue with the next iteration ✔

In Python, variables must be declared with a specific type before use.


true
false ✔
----------
A 'for' loop can be used to iterate over the elements of a list in Python.
true ✔
false
----------
Strings in Python are immutable.
true ✔
false
----------
Conditional statements in Python use the 'switch' keyword.
true
false ✔
----------
The 'print()' function can be used to write output to the console in Python.
true ✔
false
``

Loops cannot be nested in Python.


true
false ✔
----------
In Python, the 'if' statement can have an optional 'else' clause.
true ✔
false
----------
You can write data to a Word file using Python's built-in functions without any external
libraries.
true
false ✔
----------
The 'while' loop in Python continues to execute as long as its condition is True.
true ✔
false
----------
Variables in Python are case-sensitive.
true ✔
false
``

Which of the following is used to concatenate two strings in Python?


a) `&`
b) `+` ✔
c) `*`
d) `@`

What will be the output of the following code?


s = 'Python'
print(s[1:4])

a) `yth` ✔
b) `ytho`
c) `ythn`
d) `yto`

What does the `len()` function return when used on a string?


a) The number of vowels in the string
b) The total number of characters in the string ✔
c) The memory location of the string
d) The ASCII value of the string

What will the following code output?


word = 'banana'
print('a' in word)
a) `True` ✔
b) `False`
c) `None`
d) Error

CRITICAL THINKING QUESTIONS


``

1) Calculate the area of the largest square inscribed in the circle.


Write a methed to return the area of square
Hint:
a) The distance between any point of the circle and the centre is called the radius.
b) Area of Circle (‫ = )مساحة الدائرة‬r *r * 3.14 (3.14*r**2)
c) Pythagorean Theorem ‫( نظرية فيثاغورس‬Hypotenuse² = Perpendicular² + Base²)
Hypotenuse=‫الوتر‬
Prependicular=‫ضلع المثلث‬
Base= ‫قاعدة المثلث‬

2) Calculate the area of the smallest square surrounded the biggist circle with given radius.
Write a methed to return the area of square
Hint:
a) The distance between any point of the circle and the centre is called the radius.
b) Area of Circle (‫ = )مساحة الدائرة‬r *r * 3.14 (3.14*r**2)
c) Pythagorean Theorem ‫( نظرية فيثاغورس‬Hypotenuse² = Perpendicular² + Base²)
Hypotenuse=‫الوتر‬
Prependicular=‫ضلع المثلث‬
Base= ‫قاعدة المثلث‬
The opposite sides of square are parallel ‫االضالع المتقابلة في المربع متوازية‬
``

3) Find number of buttons (‫ )ازرار‬if there are always 3 red buttons fewer than white
buttons. And there are always 4 more grey buttons than the red.
Write method with one parameter (the number of white buttons) and return the number of
all the buttons.

4) There are two programs to issue the bill of electricity in Jordan as the following table.
Write a method in python to show which is the best program if you provide the average
consuming for each month.
Subsidized (‫)مدعوم‬ Unsubsidized (‫)غير مدعوم‬
<=300 kwh 5 pastries 12 pastries
<=600 kwh 10 pastries
>600 20 pastries
``

There are two solutions


1)

2)
``

5) Write recursive method to get the multiplication of two positive integer numbers without
using multiplication sign (*)

6) Write recursive method to get the remainder of two positive integer numbers without
using remainder sign (%)
``

7) Write method to find the LCM (Least common Multiple)


``

8) Write recursive method to find the next polynomial with two parameters n and x and
return the result of this polynomial P(x)=nxn+(n-1)xn−1+⋯+ x+0
``

9) Use the following shape to write method with radius as parameter


to return the area of blue area (the white area is for square

You might also like