Ece001 PDF
Ece001 PDF
in
Ahmed Abouellail
Faculty of Engineering
Sphinx University
Assiut, Egypt
2024-2025
Lecture 1
Your helpful friend ! You are not
the first one who code !
• GUI has graphical icons • CLI has a command line form to text.
• Require more memory for figures and motions. • Require less memory.
• Slower • Faster
• The appearance can be easily changed and • The appearance cannot be changed and
adapted. adapted easily and has limitations.
Experience
Synthesis
Analysis
• Ahmed → 190 cm, Ali → 150 cm
• So, Ahmed is taller than Ali.
DATA
Information
• Ahmed will be better than Ali in playing
basketball . Knowledge
• Ahmed will be an international Wisdom
basketball player; he has the attributes.
How can a computer understand languages?
Classification of Programming Languages
• A program is a list of instructions for the
computer to follow to accomplish certain tasks.
• A coded language is used by programmers to
write instructions that a computer can
understand to do what the programmer wants.
• Every coding language has its own vocabulary,
and syntax, and like real languages it requires
practice.
Calculate area of a
rectangle
Calculate area of a rectangle (Problem → Algorithm)
How can a computer solve this problem?
• I get the values of the height and the width from
you, and I store them in our memory.
→ Get height as h (Inputs)
→ Get width as w (Inputs)
• I multiply them in my brain and store the result in my
memory
→ Calculate area = h*w (Process)
• Inform you about the result value.
→ display area (Output)
Presentation of Algorithm
22
Lecture 2
Pseudocode
Examples:
• this program will request a greeting from the user. If the greeting matches a specific
response, the response will be delivered; if not, a rejection will be delivered.
• display possible responses "1. Fine." "2. Great!" "3. Not good.“
• print request for input "Enter the number that best describes you:
if "1" print response "Dandy!“
if "2" print response "Fantastic!“
if "3" print response "Lighten up, buttercup!“
if input isn't recognized print response "You don't follow instructions very well, do you?"
What is an ALGORITHM?
• The word Algorithm means “a process or set of instructions to be
followed in problem-solving operations”. Algorithms can be
expressed using flowcharts, natural language, and other
methods.
Set of
instructions
input output
to obtain the
output
What is a FLOWCHART?
• A Flowchart is a diagram of the
sequence of movements or actions of
people or things involved in a complex
system or activity. It uses
special shapes to represent different
types of actions or steps in a process.
input L
1. Input the length L of side (INPUT/OUTPUT)
2. area = L*L (PROCESS)
3. display area (INPUT/OUTPUT)
area = L*L
Display
area
Stop
2. Determine whether a temperature is
Start
below or above the freezing point
Read
1. Input temperature (INPUT/ OUTPUT) Temperature
2. If temperature is less than 0, then
print “Below freezing", otherwise
print “Above freezing" Yes Temperature No
(DECISION OF POSSIBLE OUTPUTS) < 0?
Print Print
“Below freezing” “Above freezing”
End
Start
No
c) If count < 10
d) If count = 1 End
4. Determine whether a student Start
passed the semester or not
input
S1, S2, S3, S4
1. Input grades of 4 courses S1, S2, S3
and S4 (INPUT)
Grade = (S1+S2+S3+S4)/4
2. Calculate the average grade with
formula "Grade = (S1+S2+S3+S4)/4"
(PROCESS)
3. If the average grade is less than Yes No
50, print "FAIL", ?
Grade < 50?
Stop
Start Game
?
Gamer Over
8. Develop a computer game to Start Game
Input number
(For example, 7)
play “Guess My Number” with the
user, who has only 3 chances to
tries = 3
guess the right number.
True Print
“Incorrect!” tries = tries -1
Print
“Correct!”
Gamer Over
Prepare a flowchart/pseudocode for a program
that:
1. Calculates a circle area
3. Bans you from logging into your Facebook account if password was
written wrongly more than twice
38
HOW TO INSTALL
PYTHON & IDE
Integrated
Development
Environment
Lecture 3
Essential Python Variables
Strings
• A string is traditionally a sequence of characters
(The gab is also a character).
• Example: “Hello”, “It is a true statement”, etc.
• Less operations are allowed.
Integers
• An integer is a whole number (not a fraction) that
can be positive, negative, or zero.
• Example: 71, 1245, - 80, etc
• Examples of operations: Add, Subtract, divide, etc.
Floats
• A double type can represent fractional as well as
whole values.
• Example: 10.12, 134e12, etc
• Examples of operations: Add, Subtract, divide, etc.
Your first program!
print() # display what’s between the brackets
Declaring Variables
print("Hello, friend!") You can check the variable type using type()
# display a greeting message
Code Result
>> Hello, friend!
a = "Hi"
name = "Ahmed"
age = 36
print("My name is", name, "I am", age) My name is Ahmed,
or print(f"My name is {name} I am {age}") I am 36.
Questions 3
a = 1.7
4
a = 30
2 a = int(a + 1) b = "0.25"
c = 3 a = int(a) + 1 x = a * int(b.replace("0.25","0"))
1 c += 1 a = a + 1 print(x)
c = 2
print(c) a = str(a)
print(c) >> 0
print(a)
>> 4
>> 2 >> 4
7 8
6 a = 0.9
5 a = "10" a = 1.7
a = 1.7 b=1 b=1
b=0 x = int(a) * int(b)
print(len(str(a))) x = a + str(b) c = a*b
print(x)
print(x) NOTHING
>> 3
>> 0
>> 100 10
9 a = 1.7
b = 1.1 b = "1"
c = 0.9 x=a+b
print(a) print(x)
ERROR(DEFINE a) ERROR (DIFFERENT DATA TYPES)
Lecture 4
Conditionals
An if statement is
a programming conditional
statement that, if proved
true, performs a function or
displays information. Below
is a general example of an if
statement, not specific to
any particular programming
language.
The if condition
Structure Code Result
if condition: if 2 + 2 == 4: >> I know math!
body print("I know math!")
and or not
‘x’ and ‘y’ are both True either ‘x’ or ‘y’ is True ‘x’ is not True
a = 1 a = 1 a = 3
b = 6 b = 6 if a != 6:
if a <= 3 and b == 6: if a > 2 or b > 2: print ("YES!")
print ("YES!") print("YES!") else:
else: else: print ("NO!")
print ("NO!") print("NO!")
>> YES!
>> YES! >> YES!
Example
“Guess my number”
import random # Import random module
print("Welcome to 'Guess My Number'!")
print("Think of a number between 1 and 100")
the_number = random.randint(1, 100)
guess = int(input("Take a guess: \n"))
if guess == the_number:
print("Correct guess! You are lucky!")
else:
print("Wrong guess! Hard luck!")
The computer picks a random number between 1 and 100. The player tries to guess it
and the computer lets the player know if the guess is too high, too low or right.
The difference between elif & else
• elseif → if the previous conditions were not true, then try this condition.
• else → is an action if all the previous conditions were not applied.
a = 5 a = 5
if a == 3: if a == 3:
print("Yes") print("yes")
else: elif a < 2:
print("No") print("no")
>> No NO RESULT
The important thing to note here is that, in order to get
to do that, not only b has to be True, but a has to be False.
And that’s the difference between an if...elif...else and a
series of ifs:
Note that multiple true conditions
if a:
are applying the first one! do this
elif b:
do that
elif c:
Example: Example: do something else
else:
print "none of the above"
>> 6
>> no
NO RESULT! ERROR!
(Define x)
Lecture 5
Lists Going through a range of arrays with for loop
Lists are used to store multiple The range() function generates a list of numbers, which is
items in a single variable. generally used to iterate over within for loops.
The range() function has two sets of parameters to follow:
fruit_list = ["apple", "banana", "cherry"] for i in range(4):
print(fruit_list) range(stop) i = 0
stop: Number of integers i = 1
(whole numbers) to generate,
List items are indexed, the first starting from zero. i.e:
i = 2
item has index [0], the second for i in range(0,4): i = 3
for i in [0, 1, 2, 3]:
item has index [1], etc.
range([start], stop[, step])
start: Starting number of the sequence.
To determine how many items a stop: Generate numbers up to, but not including this number.
list has, use the len() function. step: Difference between each number in the sequence
i.e.:
for i in range (0, 10, 2):
A list with strings, integers and for i in range (10, 0, -2):
boolean values: The range() function (and Python in general) is 0-index based,
meaning list indexes start at 0, not 1. eg. The syntax to access
the first element of a list is fruit_list[0]. The last integer
list1 = ["abc", 34, True, 40, "male"]
generated by range() is not included.
Examples
1 Start
2 Start
i=2 i=2
No i <= 6 No i < 11
? ?
i=i+2 i=i+3
Yes Yes
print “i” print “i”
my_list = [-5, 7, 2]
5 for x in my_list:
>>
The index
if x == max(my_list):
of the max
print(f"The index of the max number is {my_list.index(max(my_list))}")
number is 1
break
To terminate a loop, you can use break function.
>>
12 newlist = [x for x in range(10) if x < 5] [0, 1, 2, 3, 4]
print(newlist)
5 countdown = 3
while countdown > 0:
print("Hello")
break >>
Hello
While loop Loop 1
Hello
x = range(3)
6 i = 0
x = 1
Loop 2 8 while True:
Hello x = input("write number 10: ")
while i < len(x):
x = 2 if x == str(10):
print("Hello")
Loop 3 break
i = i + 1
Hello
x = 3
For loop
>> x = 1 >>
7 for x in range(3):
Hello 9 x = 2 >>
2
10 while x != 6: 3
print("Hello") while x != 6:
Hello print(x) 5
print(x) 4
Hello x = x + 2 ..
x = x + 2
ꝏ
a = 13
11 while a < 20:
>>
12 a = [2, 5, 6, 3, 66, 67, 22]
13 y = 0
print(a)
14 while a[y] < 60:
a = a+1
15 y = y + 1
if a > 15:
break print(f"The 1st number bigger than 60 : {a[y]}")
>>
The 1st number bigger than 60: 66
13 fruit_list = ["apple", "banana", "cherry"] 14 hungry = True
i = 0 while hungry:
>>
while i < len(fruit_list): print("Time to eat!")
apple
print(fruit_list[i]) hungry = False
banana
i = i + 1 cherry
>>
Time to eat
>>
15 i = 1
while i < 6: 1
print(i) 2
i += 1 3
else: 4
print("i is no longer less than 6") 5
i is no longer less than 6
16 y = 10
while True:
x = input("guess a value between 1 and 100: ")
if x == str(y):
break
import random
17 y = random.randrange(100)
while True:
x = int(input("guess a value between 0 & 100: "))
if x < y:
print("guess higher")
elif x > y: import random
print("guess lower")
18 y = random.randrange(100)
else: tries = 3
print("you win") while True:
break x = int(input("guess a value between 0 & 100: "))
if x != y:
tries -= 1
if tries == 0:
print("Game over!")
break
elif x < y:
print("Higher!")
elif x > y:
print("Lower!")
else:
print("you win")
break
menu = ["green tea", "red tea", "black tea", "nescafe", "espresso", "milkshake"]
19 print("Here is the menu:")
for item in menu:
print(f"{menu.index(item)+1}.{item}")
order = int(input("Please choose your order by typing the corresponding number.\n"))
available = ["green tea", "black tea", "nescafe", "espresso", "milkshake"]
i = 0
if 0 < order < 7:
order = menu[order-1]
while i < len(available):
if available[i] == order:
print("In the menu.")
break
i += 1
else:
print(f"{order} is unfortunately not available.")
else:
print("Please, place your order carefully.")
Questions
>> >>
Element at [1][0] = 4 Element at [2]= [7, 8, 9]
arr=[[1,2,3],[4,5,6],[7,8,9]] arr=[[1,2,3],[4,5,6],[7,8,9]]
del(arr[2][2]) del(arr[2])
for x in arr: >> or arr = arr[:2] >>
for i in x: 1 2 3 for x in arr: 1 2 3
print(i,end=" ") 4 5 6 for i in x:
4 5 6
print() 7 8 print(i,end=" ")
print()
Sheet #
Print the following list Construct a 3x3 matrix Checkout the result of
into a matrix shaped output in zeros the following code
using for loop
import numpy as np
x = [[12, 7, 3], [4 , 5, 6], [7, 8, 9]]
y = [[5, 8, 1], [6, 7, 3], [4, 5, 9]] x = [[12, 7, 3], [4, 5, 6], [7, 8, 9]]
result = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] y = [[5, 8, 1], [6, 7, 3], [4, 5, 9]]
result = np.array(x) - np.array(y)
for i in range(len(x)):
for j in range(len(x[0])): for r in result:
result[i][j] = x[i][j] + y[i][j] print(r)
result=result[:2]
for r in result:
print(r)
Questions
Question (1) Question (2) Question (3) Question (4)
arr = [[1,0], arr = [[1,2], arr=[[0,0,0], arr=[["a","b"],
[3,4]] [3,4]] [0,0,0]] ["c","d"],
["e","f"],
arr[0][1] = 2 arr.insert(2,[5, 6]) del(arr[1]) ["g","h"]]
if "year" in thisdict:
print(f"Yes, {list(thisdict.keys())[-1]} thisdict = {
is one of the keys in the thisdict "brand": "Samsung",
dictionary") "country": "South Korea",
thisdict.pop("year") "model": {
print(thisdict) "s series":"s24",
"year": 2024
}
Iterate through the }
nested dictionary only
>> for x in thisdict:
Yes, year is one of the keys in if type(thisdict[x]) == dict:
the thisdict dictionary for y in thisdict[x]:
print(y)
{'brand': 'Samsung', 'country':
'South Korea'}
>>
s series
year
Questions Question (2)
car = {
"brand": "Ford",
Question (1) "model": "Mustang",
"year": 2012
student = dict(name = "Ahmed", }
age = 18
age = 19) car.update({"color": "red"})
>> print(car)
print(student.get("age"))
19
>> car(['brand', 'model’,
'year', 'color'])
Question (3)
country_capitals = {"Jordan": "Amman", "Qatar": "Doha", "Iraq": "Bagdad"}
>>
for country in country_capitals: Amman
capital = country_capitals[country] Doha
print(capital)
Bagdad
Lecture 9
Functions
⌐ You can pass
parameters,
into a function,
which is a block
of code which
only runs when
it is called and
can return data
as a result.
def my_function(): def subject(x): def subject(sub, x):
print("Hello from a print(f"Math({x})") print(f"{sub}({x})")
function") subject(1)
my_function() subject(2) subject("Physics",1)
subject("Chemistry")
>>
Hello from a function >> >>
Math(1) ERROR!
Math(2)
>> >>
Rami is better than Ali and Noha in The best student in chess
chess. is Rami.
def square(x): def add(*numbers): def team(country =
r = x * 3 total = 0 "Egypt"):
return r for num in numbers: print(f"My FIFA
total += num team is {country}.")
print(square(3)) return total
>> team("England")
print(add(2, 3)) 5 team("Spain")
>> print(add(2, 3, 5)) 10 team()
Math(1) print(add(2, 3, 5, 7)) 17 team("Brazil")
Math(2) print(add(2, 3, 5, 7, 9))
26
>>
My FIFA team is
England.
greet = lambda name : print(f"Hi, {name}!") My FIFA team is
Spain.
greet("Ali")
My FIFA team is
⌐ Lambda also defines a Egypt.
>> function, but its body must My FIFA team is
have a single expression Brazil.
Hi, Ali!
Questions
Question (1) Question (2)
def greet(): def add_numbers(num1, num2):
print('Hello sum = num1 + num2
World!') print("Sum =", sum)
NO RESULT! >>
add_numbers(5, 4)
Sum = 9
Question (3)
def find_square(num): Question (4)
result = num * num
return result def add_numbers( a = 7, b = 8):
sum = a + b
square = find_square(3) print('Sum:', sum)
>> >>
print('Result =', square) add_numbers(1) Sum = 9
Result = 9
Lecture 10
User Interface
⌐ You can pass
parameters,
into a function,
which is a block
of code which
only runs when
it is called and
can return data
as a result.
Creating a window ⌐ First, import the tkinter module as tk to the program:
root.title("Hello!")
root.geometry('200x25')
root.mainloop()
Tkinter Button
import tkinter as tk ⌐ The command of the button is
assigned to a lambda expression
root = tk.Tk() that closes the root window.
root.title("Hello!")
root.geometry('250x50')
root.mainloop()
Tkinter Entry widget
import tkinter as tk ⌐ This creates a password
entry. When you enter a
root = tk.Tk() password, it doesn’t show
the actual characters but
root.title("Hello!") the asterisks (*) specified in
the show option.
root.geometry('250x100')
root.mainloop()
Design a login window for email
service and save user inputs
import tkinter as tk email_label = tk.Label(signin,
from tkinter.messagebox import showinfo text="Email Address:")
email_label.pack()
# root window email_entry = tk.Entry(signin,
root = tk.Tk() textvariable=email)
root.geometry("300x150") email_entry.pack()
root.resizable(False, False) email_entry.focus()
root.title('Sign In')
password_label = tk.Label(signin,
email = tk.StringVar() text="Password:")
password = tk.StringVar() password_label.pack()
password_entry = tk.Entry(signin,
def login_clicked(): textvariable=password,
msg = f"You entered email: {email.get()} show="*")
and password: {password.get()}" password_entry.pack()
showinfo(title = 'Information',
message = msg) login_button = tk.Button(signin,
text="Login",
signin = tk.Frame(root) command=login_clicked)
signin.pack() login_button.pack()
root.mainloop()
Program output:
⌐ Login window