Python - One Sheet
Python - One Sheet
In Python, variables are declared by simply assigning a value to a name using the = operator.
variable_name = value
و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
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
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 ُترِج ع دالة،بشكل افتراضي
.) لتغيير نوع البيانات إذا لزم األمر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:
``
))"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
``
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.") في البرنامج
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
Example:
CODE OUTPUT
age = 20 You are an adult.
if age >= 18:
print("You are an adult.")
age = 20
if age >= 30:
``
One-Way Decisions
age = 18 Adult
status = "Adult" if age >= 18 else
"Minor"
print(status)
Nested Decisions
``
if x < 100 :
print('All done')
Two-way Decisions
x=4 Bigger
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.
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'
Recursion Functions
that calls itself is known as a recursive function. And the process is known as recursion.
وُتعرف العملية بالتكرار،الدالة التي تستدعي نفسها بالدالة التكرارية
print_number(2)
# Example usage:
``
n=5
result = sum_of_natural_numbers(n)
print(f"The sum of the first {n} natural numbers is: {result}")
# 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!
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!')
``
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
متغير التكرار "يتكرر" عبر التسلسل (مجموعة
.)مرتبة
يتم تنفيذ كتلة (جسم) التعليمات البرمجية •
.مرة واحدة لكل قيمة في التسلسل
• يتحرك متغير التكرار عبر جميع القيم في
.التسلسل
members of a set”
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
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 .الفرعي
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
``
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
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
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)
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")
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."
# 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)
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
# Calculate BMI
bmi = calculate_bmi(weight, height)
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
# Calculate BMI
bmi = calculate_bmi(weight, height)
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
# Calculate average
gpa = total_grades / 5
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: "))
``
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: "))
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: "))
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)
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()
else:
print("No Tax")
else:
print("Wrong Entry")
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)
``
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"
# Example usage:
print(count_vowels("Hello World")) # Output: 3
``
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()
----------
``
a) `yth` ✔
b) `ytho`
c) `ythn`
d) `yto`
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
``
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 (%)
``
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
``