0% found this document useful (0 votes)
26 views106 pages

Ece001 PDF

Uploaded by

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

Ece001 PDF

Uploaded by

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

Introduction to Computer Programming (ECE001)

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 !

You will find explanations on all


levels, Just ask about any
code/syntax and you will more
than expected !
Graphical User Interface (GUI) Command Line Interface (CLI)
GUI is a user interface that allows users to interact with Command Line Interface (CLI) allows the user to
electronic devices through graphical icons. interact with the system using commands.

• GUI has graphical icons • CLI has a command line form to text.

• Even a beginner can easily handle • It needs knowledge.

• 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.

• More flexible. • Not much flexible.


Data Processing

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.

• High level languages: (C, C++, C#, Java, etc.)


Low level languages: (Assembly, etc.)

What determines a good language?


What is a program?
A programming language is like any language in the world:
Arabic, English, French, Japanese, etc.
• Both are means of communication. Whether human to
human or human to machines.

• Both have structure


- A natural language has grammatical rules.
- A programming language has STRICT syntax.
Basic Concepts
• Programming at its core is about two things:
- Defining problems
- Solving problems

• The two aspects are tightly integrated.

• To solve a problem, you first must clearly know what it


is, because a clear definition of the problem leads
you to solution.
Let’s think like COMPUTERS
You need to develop a program to

Calculate area of a rectangle

How I solve this problem as a human?


• I get the values of the height and the
width from you, and I store them in my
memory.
• I multiply them in my brain and store
the result in my memory
• Inform you about the resultant value.
Lets’ think like COMPUTERS
You need to develop a program to

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

Descriptive Analysis Flow Chart Pseudo Code

Demonstrate the Problem, Draw the sequence of Describe of the steps


identify Inputs and steps and decisions using a mix of program
outputs, define the input- needed to perform the languages with informal
output relationship process notation of actions

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.

• print greeting "Hello stranger!“

• print prompt press "Enter" to continue

• <user presses "Enter"> display "How are you today?“

• 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.

• Lines and arrows show the sequence of


the steps, and the relationships among
them. These are known
as flowchart symbols
Prepare a flowchart/Pseudocode
for the following problems
1. Find the area of a square
2. Determine whether a temperature is below or above the
freezing point
3. Print hello world 10 times
4. Determine whether A student passed the semester or not
5. Find the sum of first 5 natural numbers !!
6. Log into a Facebook account
7. Develop a computer game to play “Guess My Number” with
the user.
8. Develop a computer game to play “Guess My Number” with
the user, who has only 3 chances to guess the right number.
9. Develop a computer game to play “Guess My Number” with the user, who has only
3 chances to guess the right number. If the user’s guess is wrong, the computer
assists the user with guiding advices.
1. Find the area of a
square start

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

3. Print Hello World 10 times


count = 0

1. Initialize count = 0 (I/O) Print


2. Print “Hello world” (I/O) “Hello world”

3. count increment by 1 (PROCESS)


4. Is count < 10? if YES go to step 2 count = count + 1
else Stop (DECISION)

“?” should be:


a) If count > 10
b) Print (count = 10)
?
count < 10?
Yes

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?

4. Or else print "PASS“ (DECISION)


“Question ?” should be: Print Print
“FAIL” “PASS”
a) If Grade < 50
b) If Grade = 50
c) If Grade <= 50 End
d) If Grade > 50
Start sum = 0

5. Find the sum of first 5 natural numbers


n=0
1. Initialize sum = 0 and n = 0 (I/O)
2. Find (sum + n) and assign it to sum n=n+1
3. Increase n by 1 (COUNTER PROCESS)
4. Is n < 5 (DECISION)
5. if YES, go to step 2 sum = sum + n
Or else,
Print sum (I/O)
No
?
n = 5?

“Q3” should be:


Yes
a) If n = 5
b) If n > 5 Print “sum”
c) Print n = 5
d) If sum = n End
6. Log into a Facebook account Start

1. Enter www.facebook.com in your browser. Enter


2. Facebook Home page loads https://www.facebook.com/

3. Enter your Email ID and Password


4. Is Email ID and Password Valid Facebook home
page loads
if NO then
Display a log in error
Enter Email and Display a log in
go to step 3 password error
else
Display Facebook account
Email
Stop Display account and
home page
Yes ?
password
correct?
No

Stop
Start Game

7. Develop a computer Input number


(For example, 7)
game to play “Guess My
Number” with the user.
print “Guess
my number”

1. Initialize number = 0(I/O) Input Guess

2. Print “Guess my number!”(I/O)


3. Initialize the user’s answer to Guess False
guess (PROCESS) ?
==
number
4. Is guess = number (DECISION)
5. if YES print “Correct!” True
Or else print “Incorrect!”(I/O) Print Print
“Correct” “Incorrect”
6. Game Over

?
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.

print “Guess print “Try again


1. Initialize number = 7 and tries = 3 my number!” please!”
2. Print “Guess my number!” No
3. Initialize the user’s answer to guess input Guess
4. Is guess = number ?
tries = 0
Yes
5. if YES print “Correct!”
6. Or else print “Incorrect!” decrease Guess
==
tries by 1 number
False tries = tries -1
7. Is tries = 0? True
If NO, print “Try again, please!”
Print Print
and go to step 3 “Correct!” “Incorrect!”
1. If YES, Game Over
Gamer Over
9. Develop a computer input number
Start Game
game to play “Guess My (For example, 7)
Number” with the user,
who has only 3 chances tries = 3 print “Higher!”
to guess the right
number. If the user’s
guess is wrong, the
computer assists the user
with guiding advices. print “Lower!”
input Guess No
print “Guess
my number!” No Guess
Yes
?<
number
tries = 0
Yes
Guess False
==
number

True Print
“Incorrect!” tries = tries -1

Print
“Correct!”

Gamer Over
Prepare a flowchart/pseudocode for a program
that:
1. Calculates a circle area

2. Grades a student in a particular subject based on their scores

3. Bans you from logging into your Facebook account if password was
written wrongly more than twice

4. Runs a vending machine

5. Runs an ATM machine

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"

Getting input from the user b = 1


c = 1.1 >>
print (type(a)) <class 'str'>
name = input("What is your name?\n") print (type(b)) <class 'int'>
print("Hi, " + name + "!") print (type(c)) <class 'float'>

>> What is your name? b=a


Ahmed print(b) Hi
Hi, Ahmed!
Arithmetic Operators
Code Result Code Result

print(4+2) # addition 6 x=1 x=1


print(4-2) # subtraction 2 x=x+1 x += 1
print(4*2) # multiplication 8 print(x) print(x) 2
print(4/2) # division 2.0
print(4**2) # power 16 x=1
y=2
x += y
print(1+1)
2 print(x) 3
print(1+"1")
print("1"+"1") Error!
11 x=1
print(int(1.9))
1 y=2
print(str(1.9))
"1.9" x /= y
print(x) 0.5
print(str(1.9)+"0.1")
print(int(1.9)+0.1) 1.90.1
1.1
Working with Strings
Code Result
# This is a comment!
greeting_1 = "Hello" # assigning a string value to a variable
print(greeting_1) # display the first variable named greeting_1 Hello
greeting_2 = ", friend!" # assigning a string value to another variable
print(greeting_2) # display second variable named greeting_2 , friend!
greeting = greeting_1 + greeting_2 # combining more than a string into 1
print(greeting) # display the combining variable Hello, friend!
print(len(greeting)) # display the number of characters in the string 14
print(greeting[0]) # display the first character of the string H
print(greeting[10]) # display character number 10 (last character) e
print(greeting[-1]) # display the last character !
print(greeting.replace("friend", " Ahmed")) # replace 'friend' with 'Ahmed’ Hello, Ahmed!
greeting_new_line = greeting_1 + "\n" + greeting_2 # new line
print(greeting_new_line) # display the string divided on two lines Hello
, friend!
print(len(greeting_new_line)) # display the number of characters in the string 15

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!")

if condition: num_of_seats = 10 >> There is available places


body num_of_students = 5
else: if num_of_seats >= num_of_students:
body print("There is available places")
else:
print("No available places")

if True: >> It is true!


print("It is true!")
else:
print("This won’t get printed.")

if 3 in [3, 4, 6]: >> Yes!


print("Yes!")
Comparison Operators
• Is equal to: ==
• Greater than: >
• Lesser than: <
• Greater than or equal to : >=
Code Result • Lesser than or equal to: <=
a = 3 >> b is greater than a
b = 7
c = 5
if b > a:
print("b is greater than a")

a = 3 >> b is not greater than a


b = 7
c = 5
if b <= a:
print("b is greater than a")
else:
print("b is not greater than a")

a = 3 >> Both conditions are True


b = 7
c = 5
if a < b and c > a:
print("Both conditions are True")
Logical Operators

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"

is exactly the same as


a = 1 a = 1
if a > 0: if a < 0: if a:
print("X") print("X") do this
elif a < 2: elif a < 2: if (not a) and b:
print("Y") print("Y") do that
elif a != 3: elif a != 3: if (not a) and (not b) and c:
print("Z") print("Z") do something else
if (not a) and (not b) and (not c):
print "none of the above"

As you can see, the elif...else notation allows you to write


>> X >> Y the same logic (the same control flow) without repeating
the a condition over and over again
Questions
Question (1) Question (2) Question (3) Question (4)
a = 1 a = 1 a = 2 a = 1.1
b = 6 b = 5 a += 1 a = int(a)
if a > 2 and b > 1: b += 1 b = 7 b = 3
a = 2 if a <= 2 and b > 3: if a < 2: if a <= 2 or b < 3:
print("yes") print(b) print(a) a = "x"
else: else: a = a + 3 print(x)
print("no") print(a) elif a >= 7: else:
a = 3 print(b) print("no")

>> 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”

End >> End


>>
2 2
4 5
6 8
>>
for i in range(3): >> 4 for a in range(15, 10, -1):
3 print(i) 0 if a == 13:
15
14
1 continue 12
2 print(a) 11
To skip a loop, you can use continue function.

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.

6 list_1 = range(6, 0, -2) >> 7 list_1 = [1, 8, 5] >>


list_2 = [] 2 list_1.sort(reverse=True) 8
for x in list_1: 4 list_1 = sorted(list_1, reverse=True) 5
list_2.append(x) 6 for i in list_1: 1
list_2.sort() print(i)
for i in list_2:
print(i)
8 i = ["C", "R", "7"] >>
print(i) ['C', 'R', '7’]
i[0:2] = ["MO"] 9 sum = 0
i[1] = "11" a = [6, 1, 4, 3, 1, 5, 0, 14]
print(i) ['MO', '11’] a.pop(a.index(max(a)))
i.insert(1, "Salah") a.remove(min(a))
print(i) ['MO', 'Salah', '11’] print(a)
j= ["EGYPT"] for i in range(len(a)):
i.extend(j) ['MO', 'Salah', sum = sum + int(a[i])
print(i) '11’,’EGYPT’] print(sum)
for x in i:
if len(x)<3: MO
print(x) 11 >>
[6, 1, 4, 3, 1, 5]
20

10 for x in [32, 34, 41, 39, 35]: >>


if x > 40: Temperature: 32 Celsius
x = "ERROR!" Temperature: 34 Celsius
if type(x) == int: Temperature: 41 Celsius
b =[f"Temperature: {x} Celsius"] Temperature: 39 Celsius
print(b) Temperature: 35 Celsius
fruits = ["apple", "banana", "cherry", "kiwi", "mango"] >>
11 ['hello', 'hello', 'hello',
newlist = ["HELLO".lower() for x in fruits]
print(newlist) 'hello', 'hello']

>>
12 newlist = [x for x in range(10) if x < 5] [0, 1, 2, 3, 4]
print(newlist)

13 fruits = ["apple", "banana", "cherry", "kiwi", "mango"] >>


newlist = [] ['APPLE', 'BANANA', 'MANGO']
for x in fruits:
if "a" in x:
newlist.append(x.upper())
print(newlist)

14 name_list = ["ahmed", "andrew", "sarah", "enjy", "reham"] >>


new_list = [] ['Ahmed', 'Andrew',
for x in name_list: 'Sarah', 'Reham']
if "a" in x:
new_list.append(x.capitalize())
print(new_list)
Questions
Question (1) Question (2) Question (3)
for i in range(1, 5): for a in range(5, 0, -1): for i in [1, 2, 3]:
if i < 3: print(a) print("Start")
i = i + 1 break
if a == 3:
print(i)
print(i) break print("End")
>> >>
2 5 >>
3 4 Start
3

Question (4) Question (5) Question (6)


sum = 0 for a in range(1, 3): for x in [1, 3, 9]:
a = [1, 2, 3, 4, 5] if 0 <= a < 2: x = x + 1
for i in range(len(a)): print(a) print(f"Value:{x}")
sum = sum + a[i] else:
print(sum) print(a**2)
>>
>> Value:2
>> 1 Value:4
15 4 Value:10
Lecture 6
While Loop 1 i = 3
while i > 0:
>>
Hello
2 i = 3
while i == 0:
NO
RESULT!
• If the condition is true, the print("Hello") Hello
print("Hello")
execution of the statement i = i - 1 Hello
i = i - 1
will be executed forever,
and will be repeated until
the condition becomes false. 3 countdown = 3 ꝏ LOOP!
while countdown > 0:
• For loop has a counter, While print("Hello!") ❖ What is the solution of an infinite loop?
loop has a condition. → A condition inside
→ break
while condition:
action
4 countdown = 3
while countdown > 0:
>>
Hello
print("Hello") Hello
countdown = countdown - 1 Hello

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

Question (1) Question (2) Question (3) Question (4)


x = 2 x = 5 a = 2 x = 3
while x != 8: a = 1 b = 5 c = 3.0
print(x) if x >= 2 or a > 2: if a <= 2 or b < 3: if int(c) == float(c):
x = x + 2 x = 2 a = "x" c = 1
while x != 9: else: elif c > 2:
>> print(x) print("no") c = 5
2 x = x + 2 while x > 4: while x > c:
4 print(x) print(x)
6 ꝏ LOOP! x = x + 2 x = x - 1
ERROR!
Define x >>
3
2
Lecture 7
2D Arrays
Nested Lists/ Nested loops
A 2D array in
python is a two-
dimensional data
structure used for
storing data
generally in a
tabular format.
Accessing Single Element Accessing an Internal Array
arr=[[1,2,3],[4,5,6],[7,8,9]] arr=[[1,2,3],[4,5,6],[7,8,9]]
print("Element at [1][0] =", arr[1][0]) print("Element at [2]=",arr[2])

>> >>
Element at [1][0] = 4 Element at [2]= [7, 8, 9]

Traversing Values in Python 2D Array


The end parameter in
arr=[[1,2,3],[4,5,6],[7,8,9]] >> the print function is
for x in arr: 1 2 3 used to add any string.
for i in x: 4 5 6 At the end of the
print(i, end=" ") 7 8 9 output of the print
print() statement in python.
Adding a New Element in the Inner Array
arr = [[1,2,3],[4,5,6],[7,8,9]]
>>
arr[1].insert(2,12)
for x in arr: 1 2 3
for i in x: 4 5 12 6
print(i,end=" ") 7 8 9
print()

Adding a New Element in the Outer Array


arr = [[1,2,3],[4,5,6],[7,8,9]] >>
arr.insert(3,[10, 11, 12]) 1 2 3
for x in arr: 4 5 6
for i in x:
7 8 9
print(i,end=" ")
print() 10 11 12
Updating a Single Element Updating an Element in the Outer Array
arr=[[1,2,3],[4,5,6],[7,8,9]] arr=[[1,2,3],[4,5,6],[7,8,9]]
arr[1][2]=16 new_arr=["four","five","six"]
for x in arr: >> arr[1]=new_arr >>
for i in x: 1 2 3 for x in arr: 1 2 3
print(i,end=" ") 4 5 10 for i in x: four five six
print() 7 8 9 print(i,end=" ") 7 8 9
print()

Deleting a Single Element Deleting an Element in the Outer Array

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

arr = [[23,45,43,23,45], a = [0] * 3 n = 10


[45,67,54,32,45], for i in range(3): a = [0] * n
[89,90,87,65,44], a[i] = [0] * 3 for i in range(n):
[23,45,67,32,10]] a[i] = [0] * n
for i in range(n):
Change the value of the for j in range(n):
second element in the if i < j:
for x in arr: second row into 1. a[i][j] = "-"
for i in x: elif i > j:
print(i, end=" ") a[i][j] = "/"
print() a[1][1] = 1 else:
Print it a[i][j] = "*"
print(a) for x in a:
for i in x:
print(i, end=" ")
print()
Write a program to add two matrices using Multiply matrices using numpy library
nested 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)

for r in result: Remove the last row in the resulted


print(r) matrix

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"]]

for x in arr: for x in arr: for x in arr: print(arr[1][2])


print(x) for i in x: print(x)
print(i,end=" ")
print()
>> >>
[1, 2] [0, 0, 0] ERROR!
>>
[3, 4] (index out
1 2
3 4 of range)
5 6
Lecture 8
Dictionaries
Dictionaries are
used to store data
values in
key:value pairs,
which are
changeable and
do not allow
duplicates.
thisdict = dict(brand = "Samsung", country = "South Korea", year = 2024)
thisdict = {
"brand" : "Samsung",
"country": "South Korea",
"year" : 2021,
"year" : 2022
} # redeclare the variable & redeclare "year"

print(thisdict) # print the variable


print(type(thisdict)) # print the data type of the variable
print(len(thisdict)) # print the amount of elements in the dictionary

print(thisdict["country"]) # print the "country" value


print(thisdict.get("country")) # print the "country" value

thisdict["year"] = "2023" # update the "year" value


thisdict.update({"year": 2024}) # update the "year" value

thisdict["color"] = "blue" # add a dictionary item


thisdict.update({"color": "black"}) # add a dictionary item

print(thisdict.keys()) # print dictionary keys


print(thisdict.values()) # print dictionary values
print(thisdict.items()) # print dictionary items
Going through a range of arrays with for loop
thisdict = dict(brand = "Samsung", country = "South Korea", year = 2024)

Iterate through keys Iterate through values Iterate through dictionary


items
for x in thisdict: for x in thisdict:
print(x) print(thisdict[x])
print() print() for x in thisdict.items():
print(x)

for x in thisdict.keys(): for x in thisdict.values():


print(x) print(x)
print() print()

>> >> >>


brand Samsung ('brand', 'Samsung')
country South Korea ('country', 'South Korea')
year 2024 ('year', 2024)
thisdict = dict(brand = "Samsung",
country = "South Korea",
year = 2024)

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)

def player(student1, student2, student3): def player(*students):


print(f"{student3} is better than {student1} and print(f"The best student in
{student2} in chess.") chess is {students[2]}.")

player(student1 = "Ali", student2 = "Noha", player("Ali", "Noha", "Rami")


student3 = "Rami")

>> >>
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:

⌐ Second, create an instance of the tk.Tk class/object


import tkinter as tk that will create the application window. By default,
the main window in Tkinter is called root, but you
root = tk.Tk() can use any other name.
root.mainloop()
⌐ Third, call the mainloop() of the main window
object. It ensures the main window remains visible
on the screen.

⌐ If you don’t call mainloop(), the main window will


display and disappear almost instantly – too quickly
to perceive its appearance. So, it ensures the main
window continues to display and run until the user
closes it.

⌐ Typically, in a Tkinter program, you place the call to


mainloop() as the last statement after creating the
widgets.
Displaying a label
⌐ Now, let’s place a
import tkinter as tk
components (widgets) on the
window.
root = tk.Tk()

root.title("Hello!")

message = tk.Label(root, text="Hello, World!")


message.pack()

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')

message = tk.Label(root, text="Hello, World!")


message.pack()

btn = tk.Button(root, text = "Click me!" , command


= lambda: root.quit())
btn.pack()

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')

message = tk.Label(root, text="Enter 4-digit passcode")


message.pack()

textbox = tk.Entry(root, textvariable = tk.Entry(root,


text="This is Entry Widget"), show = "*")
textbox.pack()

btn = tk.Button(root, text = "Sign in" , command =


lambda: root.quit())
btn.pack()

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

⌐ Login popup message

You might also like