Python - Lecture 1
Python - Lecture 1
n
The Easy
Way
Lecturer
Dr. Aya Abdelaziz Ismail
Course
Objectives
Easy To Rapid
learn Development
General
Purpose
Language
Python 2 or
3
Python 2 is the legacy, Python 3 is the future of the
language
How does python
work?
HPW
Compiler vs
Interpreter
Compiler: translates the entire program from a high-level programming language into
machine code before the program is executed. The result is an executable file that can be
run independently of the original source code. EX: C, C++
Output
compil Executo
er r
Object
Source Code
Code
Interpreter: An interpreter translates and executes the program line by line, one
statement at a time, at runtime. It does not produce a separate machine code file; instead,
it directly executes the high-level code.
Interpret
Output
er
Source
Code EX: Python is Interpreted
Language
Feature Compiler Interpreter
print(“Hello, World”)
Output:
Hello, World
Synta
x
Python Syntax
Rules
Synta
Identifiers x
Rules
A Python identifier is a name used to identify a variable,
function, class, module or other object
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield
Synta
Line x
Indentations
Level 1
Level 2
if True:
print(“Hello, World”)
else:
print(“Bye, World”)
No ;
Just Line
Indentation
Synta
Quotes … 1.. x
2 ... 3
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and
sentences."""
Synta
Commen x
ts
# this is a comment
Variables & Data
Types
Python is loosely typed
language
Variables and Data
Declare a Types
Variable
name = “Ahmed”
age = 17
isStudent = True
age = “seventeen”
Variables and Data
Data Types
Types
Strings
Numbers
Boolean
Tuples
Lists
Dictionaries
type(variable_name)
Variables and Data
Type Types
Conversion
age = 17.5
int(age) # 17
float(age) # 17.5
str(age) # “17.5”
Operator
s
Operator
Arithmet s
ic
+ addition Op 2 + 3 #output: 5
- Subtraction Op 4 – 2 #output: 2
* Multiplication Op 4 * 5 #output: 20
= assig x = 4 #output: 4
n
+= add and assign x += 3 #output: 7
>
!= return
return True
True ifif aa greater
not equals b
than b
< return True if a lesser
than b
Comparison
== operators
Examples
True = 1, False = 0
No n e , F a l se , 0 , Em p t y
co l l ect i o n s: “”, (), [],
{}
Boolean
More Examples: Operators
2 and 1 #output: 1
Note: The output is 1 because both 2 and 1 are truthy values, and the and operator returns
the last truthy value it evaluates, which is 1 in this case.
2 and 0 #output: 0
0 and 2 #output: 0
1. The and operator evaluates the left-hand operand first. If it is False or a falsy
value (like 0, None, False, or an empty list), it returns that value.
2. If the left-hand operand is truthy (any non-zero number, non-empty object, etc.),
it then evaluates the right-hand operand. If both are truthy, it returns the value of
the right-hand operand.
Boolean
More Examples: Operators
2 or 1 #output: 2
False or 0 #output: 0
String
s
Play with
Strings
String
How s
To
These options can be used to define a
string; single-line strings:
name = “Ahmed”
---or---
name = ‘Ali’
string1 = "I'm Ahmed" # Using double quotes to avoid escaping the single quote
string2 = 'He said "Hello"' # Using single quotes to avoid escaping double quotes
Both triple single (''') and triple double
(""") quotes are used for multi-line strings
# or
multi_line_string = """This is a string
that spans
multiple lines."""
String
Play String concatenation and slicing s
!
name = “Ahmed ”
print(name) # Ahmed
# String concatenation using operator +
print(name[1:3]) #
hm
print(name[:4]) # Ahme
String
Method s
s name = “information technology institute”
len(name) #32
order.replace(“info”, “”,2)
digits.isDigit() # True
containDigits.isDigit() # False
String
String s
Formatting
str.format(*args,**kwargs): substituting placeholders {}
with specified values.
Example
int 18
float 18.5
complex
19+4j
Number
Type s
Conversion
int int(“18”)=18
float
float(15)=15.0
complex
complex(4,5)=4+5j
Number
Play s
!
w, x, y, z = 4, 4.4, 4.6, 15
round(y) #output: 5
max(x,y,z) #output: 15
Data
Structures
Data
Structures
list
s
List
Intr s
o
A collection of various data
types
newList = []
Lists are mutable, meaning you can modify them after they are created. This includes
adding, removing, or changing elements in the list.
newList = [1, “hi”, True]
How to access its elements?
newList[0] #1
#”Hi”
newList[1] #True
#Inde
x
List
Method s
s
myList = [“C”, “JavaScript”, “Python”, “Java”, “php”];
myList myList.pop(4)
C
JavaScript
Python
Java
List
Method s
s
myList = [“C”, “JavaScript”, “Python”, “Java”, “php”];
myList myList.pop(4)
C
myList.append(“go”)
JavaScript
Python
Java
go
List
Method s
s
myList = [“C”, “JavaScript”, “Python”, “Java”, “php”];
myList myList.pop(4)
C
myList.append(“go”)
JavaScript
myList.insert(3, ‘Scala’)
Python
Scala
Java
go
List
Method s
s
myList = [“C”, “JavaScript”, “Python”, “Java”, “php”];
myList.pop(4)
myList
myList.append(“go”)
JavaScript
myList.insert(3, ‘Scala’)
Python
myList.remove(“C”)
Scala
Java
go
go
List
Method s
s
myList = [“C”, “JavaScript”, “Python”, “Java”, “php”];
myList.pop(4)
myList
myList.append(“go”)
JavaScript
myList.insert(3, ‘Scala’)
Python
myList.remove(“C”)
Scala
go
go myList.extend(yourList) # appends each
Rub
Ruby element of yourList to the end of
y
Rust
myList
List
Method s
s
myList = [“C”, “JavaScript”, “Python”, “Java”, “php”];
myList.pop(4)
myList
myList.append(“go”)
JavaScript
myList.insert(3, ‘Scala’)
Python
myList.remove(“C”)
Scala
go
go myList.extend(yourList) # appends each
Rub
Ruby element of yourList to the end of
y
C++
myList
myList[6]=“C++”
Data
Structures
Tuple
s
Immutable
Lists
Tuple
Intr s
o Same as Lists but Tuples are immutable
Dictionari
es
Key/ value Pairs
Dictionari
Intr es
o
A key: value comma seperated elements Data
Structure
newDict = {}
infoDict.update(addInfoDict)
if (x == 2):
print(“Two”)
elif (x == 3):
print(“Three”)
else:
print(“others”)
Control
for … Flow
in
for loop is used to iterate over a sequence (like a list, tuple, string, or range).
Output:
JavaScript
Python
Java
Range Control
Flow
Function
Syntax of range(): range([start], end[, step])
Parameters:
1.start (optional):
•The starting value of the sequence. If not specified, it defaults to 0.
range(5) #0,1,2,3,4
range(0,5,1) #0,1,2,3,4
range(1,10,2) #1,3,5,7,9
#The range object is an iterable, meaning you can loop over it (using for)
for i in range(10):
print(i)
0 1 2 3 4 5 6 7 8 9
Control
whil Flow
e
dayCount = 0
while dayCount < 4:
print(“We are learning Python”)
dayCount += 1
Output: DayCount
We are learning Python 1
We are learning 2
Python 3
We are learning Python 4
We are learning
Python
Control
Break Flow
Statement
The break statement: is used to exit a loop before reaching its natural end
for i in range(10):
if (i == 5):
break
print(i)
0 1 2 3 4
Control
Continue Flow
Statement
used inside loops to skip the rest of the code inside the loop for the current iteration and
move on to the next iteration.
for i in range(10):
if (i == 5):
continue
print(i)
0 1 2 3 4 6 7 8 9
Control
Else Flow
Statement
else statement can be used in
for i in range(10): conjunction with loops (for and
while) in Python :
if (i == 5):
else: is executed when the loop
continue completes normally.
0 1 2 3 4 6 7 8 9 1
0
Control
Else Flow
Statement
my_list = [1, 2, 3, 4, 5]
for item in my_list:
•If item == 3 is found, the break statement stops
if item == 3:
the loop, and the else block is not executed.
print("Item found!")
•If the loop finishes without finding 3, the else
break block will run, printing "Item not found".
print(item)
else:
print("Item not found")
1 2 Item found!
Control
Pass 0 Flow
Statement done
1
done
else:
4 print(i)
done
done Print(“done”)
6
done
7
done
8
done
9
done
Python
input I/O
Function
input(prompt_message)
Example
Output:
// Function calling
fnX()
fnX()
Functio
Definin ns
g
def fnName:
pass
Function
Calling It
doSum(2) # output: 7
doSum(2,4) # output: 9
doSum(2,4,10) # output: 16
Functio
*argumen ns
ts # Define a function that accepts any number of argument
The *args syntax allows the function to accept any number of positional arguments
as a tuple.
def doSum(*args):
sum = 0
for i in args:
sum += i;
print(sum)
Calling It
doSum(2,6) # output: 8
doSum(2,4,5,15) # output: 26
Functio
**keywor ns
ds
# Define a function that accepts any number of keyword
arguments
def doSum(**kwargs):
#Loop through each key in the keyword arguments dictionary
for k in kwargs:
# Print the value associated with the key
print(kwargs[k])
Calling It
outer()
print(x) # Refers to the global 'x'
• Inner functions have access to variables defined in their enclosing
functions (outer scopes).
EX:
def outer_function():
outer_var = 'Hello' # Outer scope variable
def inner_function():
inner_var = 'World' # Inner scope variable
print(outer_var) # Accessing the outer scope variable from inner
function
inner_function()
outer_function()
Output
Hello
Global Scope: Variables defined at the top level of a script or module.
- The global keyword allows you to modify these global variables inside functions.
EX:
def modify_global():
global global_var
global_var = 'Modified global' # Modifying a global variable inside a function
It is particularly useful for nested functions when you need to modify a variable from
the outer (but non-global) function.
Ex:
def outer_function():
outer_var = 'Original'
def inner_function():
nonlocal outer_var
outer_var = 'Modified'
print('Inside inner_function:', outer_var)
inner_function()
print('Inside outer_function:', outer_var)
output
Inside inner_function: Modified
outer_function() Inside outer_function: Modified
Scop
Lexical e
Scope
In lexical scoping, the scope of a variable is determined by its position in the source code at the
time of writing, not at runtime.
Global Scope
Output:
Scop
Lexical e
Scope
name = “Ahmed” Global Scope
name = “Ahmed”
Output:
Scop
Lexical e
Scope
name = “Ahmed” Global Scope
def outerFn():
name = “Ahmed”
name = “Ali”
def innerFn():
print(name)
innerFn()
Output:
Scop
Lexical e
Scope
name = “Ahmed” Global Scope
def outerFn():
name = “Ahmed”
name = “Ali”
def innerFn():
outerFn Scope
print(name)
innerFn()
outerFn()
Output:
Scop
Lexical e
Scope
name = “Ahmed” Global Scope
def outerFn():
name = “Ahmed”
name = “Ali”
def innerFn():
outerFn Scope
print(name)
innerFn() name = “Ali”
outerFn()
Output:
Scop
Lexical e
Scope
name = “Ahmed” Global Scope
def outerFn():
name = “Ahmed”
name = “Ali”
def innerFn():
outerFn Scope
print(name)
innerFn() name = “Ali”
Output:
Scop
Lexical e
Scope
name = “Ahmed” Global Scope
def outerFn():
name = “Ahmed”
name = “Ali”
def innerFn():
outerFn Scope
print(name)
innerFn() name = “Ali”
Output:
Scop
Lexical e
Scope
name = “Ahmed” Global Scope
def outerFn():
name = “Ahmed”
name = “Ali”
def innerFn():
outerFn Scope
print(name)
innerFn() name = “Ali”
nam
e
Output: ???
Scop
Lexical e
Scope
name = “Ahmed” Global Scope
def outerFn():
name = “Ahmed”
name = “Ali”
def innerFn():
outerFn Scope
print(name)
nam
name = “Ali”
innerFn() e
outerFn() ???
innerFn Scope
Output:
Scop
Lexical e
Scope
name = “Ahmed” Global Scope
def outerFn():
name = “Ahmed”
name = “Ali”
def innerFn():
outerFn Scope
print(name)
nam
name = “Ali”
innerFn() e
outerFn() ???
innerFn Scope
Output:
Ali
Scop
Lexical e
Scope
name = “Ahmed” Global Scope
def outerFn():
name = “Ahmed”
name = “Ali”
def innerFn():
print(name)
innerFn()
oute
rFn()
print(name)
Output:
Ali
Scop
Lexical e
Scope
name = “Ahmed” Global Scope
Output:
Ali
Scop
Lexical e
Scope
name = “Ahmed” Global Scope
Output:
Ali
Ahmed
Scop
global e
Keyword
name = “Ahmed” Global Scope
def outerFn():
name = “Ahmed”
global name
name = “Ali”
outerFn Scope
def innerFn():
print(name)
innerFn()
outerFn()
Output:
Scop
global e
Keyword
name = “Ahmed” Global Scope
def outerFn():
name = “Ahmed”
global name
name = “Ali”
outerFn Scope
def innerFn():
print(name)
innerFn()
outerFn()
Output:
Scop
global e
Keyword
name = “Ahmed” Global Scope
def outerFn():
name = “Ahmed”
global name
name = “Ali”
outerFn Scope
def innerFn():
print(name)
innerFn()
outerFn()
Output:
Scop
global e
Keyword
name = “Ahmed” Global Scope
def outerFn():
name
name==“Ahmed”
“Ali”
global name
name = “Ali”
outerFn Scope
def innerFn():
print(name)
innerFn()
outerFn()
Output:
Scop
global e
Keyword
name = “Ahmed” Global Scope
def outerFn():
name
name==“Ahmed”
“Ali”
global name
name = “Ali”
outerFn Scope
def innerFn():
print(name)
innerFn() innerFn Scope
outerFn()
Output:
Scop
global e
Keyword
name = “Ahmed” Global Scope
def outerFn():
name
name==“Ahmed”
“Ali”
global name
name = “Ali”
outerFn Scope
def innerFn():
print(name)
innerFn() innerFn Scope
outerFn()
Output:
Scop
global e
Keyword
name = “Ahmed” Global Scope
def outerFn():
name
name==“Ahmed”
“Ali”
global name
name = “Ali”
outerFn Scope
def innerFn():
print(name)
innerFn() innerFn Scope
outerFn()
nam
e
Output: ???
Scop
global e
Keyword
name = “Ahmed” Global Scope
def outerFn():
name
name==“Ahmed”
“Ali”
global name
name = “Ali”
outerFn Scope
def innerFn():
nam
print(name) e
innerFn() ???
innerFn Scope
outerFn()
Output:
Scop
global e
Keyword
name = “Ahmed” Global Scope
Output:
Scop
global e
Keyword
name = “Ahmed” Global Scope
Output:
Ali
Scop
global e
Keyword
name = “Ahmed” Global Scope
Output:
Ali
Scop
global e
Keyword
name = “Ahmed” Global Scope
Ali
Scop
nonlocal e
Keyword
name = “Ahmed” Global Scope
def outerFn():
name = “Ahmed”
name = “Ali”
def innerFn():
outerFn Scope
nonlocal name
print(name) name = “Ali”
name = “Sara”
innerFn()
print(name)
outerFn()
Output:
Scop
nonlocal e
Keyword
name = “Ahmed” Global Scope
def outerFn():
name = “Ahmed”
name = “Ali”
def innerFn():
outerFn Scope
nonlocal name
print(name) name = “Ali”
Output:
Scop
nonlocal e
Keyword
name = “Ahmed” Global Scope
def outerFn():
name = “Ahmed”
name = “Ali”
def innerFn():
outerFn Scope
nonlocal name
print(name) name = “Ali”
Output:
Scop
nonlocal e
Keyword
name = “Ahmed” Global Scope
def outerFn():
name = “Ahmed”
name = “Ali”
def innerFn():
outerFn Scope
nonlocal name
print(name) name = “Ali”
Output:
Ali
Scop
nonlocal e
Keyword
name = “Ahmed” Global Scope
def outerFn():
name = “Ahmed”
name = “Ali”
def innerFn():
outerFn Scope
nonlocal name
print(name) name = “Ali”
Output:
Ali
Scop
nonlocal e
Keyword
name = “Ahmed” Global Scope
def outerFn():
name = “Ahmed”
name = “Ali”
def innerFn():
outerFn Scope
nonlocal name
print(name) name
name == “Sara”
“Ali”
Output:
Ali
Scop
nonlocal e
Keyword
name = “Ahmed” Global Scope
def outerFn():
name = “Ahmed”
name = “Ali”
def innerFn():
outerFn Scope
nonlocal name
print(name) name
name == “Sara”
“Ali”
Output:
Ali
Scop
nonlocal e
Keyword
name = “Ahmed” Global Scope
def outerFn():
name = “Ahmed”
name = “Ali”
def innerFn():
outerFn Scope
nonlocal name
print(name) name
name == “Sara”
“Ali”
Output:
Ali
Sara
Tips and
Tricks
Tips and
Shorthand Tricks
If
Example
canFly = True
bird = “Dove” if canFly else “Penguin”
Traditional Way
x = 4
y = 5
temp = x
x = y
y = temp
Python Way
x,y = 4,5
x,y = y,x
Enhanced Tips and
Tricks
Print • By default, print() adds a newline (\n) after
printing,
print("I'm", end=" ") • but with end=" ", it adds a space instead, so
that the next print() statement continues on
the same line.
print("Ahmed", end=".")
Output:
output
True # a == b (values are the same)
False # a is b (different objects in memory)
True # a is c (same object in memory)
Tips and
Tricks
is vs ==
True == 1 # True
True is 1 # False
list1 = [1,2,3]
list2 = [1,2,3]
#are two different lists with the same values.
The == operator checks if the contents of the lists are equal, which is true.
list1 == list2 # True#
# two different lists that occupy different places in memory, even though they have
#the same values.
list1 is list2 # False
Tips and
Sequence Tricks
Unpacking
l = [1,13,3,7]
a,b,c,d = l
# a=1,b=13,c=3,d=7
a,*b,c = l
# a=1,b=[13,3],c=7
Tips and
enumerate Function: Tricks
Useful: when you need to perform operations based on both the index (position) and the
value in a loop.
Output:
Element Value: JavaScript, Element index: 0
Element Value: Python, Element index: 1
Element Value: Java, Element index: 2
Tips and
all & Tricks
anyall(): check if all items in an iterable are truthy value.
Returns True if all elements in the iterable are True (or if the iterable is
empty). Otherwise, returns False
#True
Thank
You