0% found this document useful (0 votes)
9 views

Python - Lecture 1

Uploaded by

Aya Ismail
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Python - Lecture 1

Uploaded by

Aya Ismail
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 121

Pytho

n
The Easy
Way

Lecturer
Dr. Aya Abdelaziz Ismail
Course
Objectives

Learn about Python, its


uses and really
understand it.
Python
Inventor

guido van rossum


Why
Python

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

Translates the entire program Translates one statement at a


Translation Method
at once time
Generates a standalone Executes directly, no
Output
executable file executable file
After compilation, run Each run requires
Execution
multiple times interpretation
Faster execution after Slower, as each line is
Speed
compilation interpreted
Errors are detected during Errors are detected during
Error Detection
compilation execution
Can use more memory for
Memory Usage Typically uses less memory
interpreter
Hello World
Program

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

Starts only az AZ _


with:

Can’t Punctuations Characters


Contain :

Can digits az AZ _


C ontain:

Python is Case Sensitive


Language
Synta
Reserved x
Words
A Python identifier doesn’t be one of these
words

and exec not

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

Variable Identifier = Variable Value

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

/ Division 16 / 5 #output: 3.2


Op
% Modulus 16 % 5 #output: 1
Op
// Division without 16 // 5 #output: 3
Fractions
** Exponent 2 ** 4 #output: 16
Op
Operator
Assignme s
nt

= assig x = 4 #output: 4
n
+= add and assign x += 3 #output: 7

-= subtract and assign x -= 2 #output: 5

*= multiply and assign x *= 6 #output: 30

/= divide and assign x /= 2 #output: 15

%= get modulus and x %= 8 #output: 7


assign
//= floor divide and x //= 3 #output: 2
assign
**= get exponent and x **= 4 #output: 16
assign
Operator
Compariso s
n
a <op> b

== return True if a equals b

>= return True if a equals or greater


than b

<= return True if a equals or lesser


than b

>
!= return
return True
True ifif aa greater
not equals b
than b
< return True if a lesser
than b
Comparison
== operators
Examples

When using == Python assume


that:

True = 1, False = 0

2 == “2” #output: False

True == “True” #output: False

False == 0 #output: True

True == 1 #output: True

True == 2 #output: False


Boolean
Operators
Expression (Logic Gate)
Expression
Boolean
Logic Operators
Gates
and AND Logic
Gate
or OR Logic
Gate
not Not Logic
Gate

True and False #output: False

True or False #output: True

not False #output: True

not (True == 2) #output: True

(False == 0) and (True == 1) #output: True


Boolean
Falsy Values: Operators

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

“Google” and 1 #output: 1

“” and “Go” #output: “”

Logical and Operator:

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

not 4 #output: False

not 0 #output: True

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

multi_line_string = '''This is a string


that spans
multiple lines.'''

# 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 +

fullName = “Mohamed ” + name * 3 + “ Ali”

print(fullName) # Mohamed Ahmed Ahmed Ahmed Ali

nameIntro = “I’m ” + fullName

print(nameIntro) # I’m Mohamed Ahmed Ahmed


Ahmed Ali
#slicing
# Starting count from index 0
print(name[4]) # d

print(name[1:3]) #

hm

print(name[:4]) # Ahme
String
Method s
s name = “information technology institute”

name.capitalize() # Information Technology Institute

len(name) #32

order = “Go read info about his work info in ” + name

order.replace(“info”, “”,2)

# Go read about his work in information technology institute

# 2 means: This is the count argument, indicating that

only the first 2 occurrences of "info" should be replaced.

digits,containDigits = “0102002932”, “Tel0102002932”

digits.isDigit() # True

containDigits.isDigit() # False
String
String s
Formatting
str.format(*args,**kwargs): substituting placeholders {}
with specified values.

-- This method can use both positional arguments (*args) and


keyword arguments (**kwargs) to dynamically format a string.

Example

intro = “My Name is {0}”


intro.format(‘Ahmed’)
# My Name is Ahmed

intro = “My Name is {1}, I work at {0}”


intro.format(‘ITI’,‘Ali’)
# My Name is Ali, I work at ITI

intro = “My Name is {name}, I work at


{place}”
Number
s
Play with
Numbers
Number
Type s
s

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(x) #output: 4 # Round a floating-point number to the nearest integer.

round(y) #output: 5

min(x,y,z) #output: 4.4

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

Java yourList = [“Ruby”, “Rust”];

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

Java yourList = [“Ruby”, “Rust”];

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

Tuples are immutable, meaning once a tuple is created, it cannot be


modified.
You cannot add, remove, or change elements in a tuple after it has been
defined.
newTuple = ()
t = (1, “hi”, True)
t[1]
# hi
t[1] = 4
# can’t
#modify
#tuple
#elements
TypeError:
Data
Structures

Dictionari
es
Key/ value Pairs
Dictionari
Intr es
o
A key: value comma seperated elements Data
Structure

newDict = {}

d = {“name”: “Ahmed”, “track”: “OS”}


d[“name”]
# Ahmed
d[“name”] = “Ali”
# {name: “Ali”,
track: “OS”}
Dictionari
Method es
s infoDict = {'track': 'OS', 'name': 'Ahmed', 'age': 17}

# provides a view of the dictionary's keys

infoDict.keys() # dict_keys(['track', 'name', 'age'])

# Search a key in dictionary:

‘name’ in infoDict # True


# returns a view object of key-value pairs (as tuples) from the dictionary
infoDict.items()

# dict_items([('track', 'OS'), ('name', 'Ahmed'), ('age', 17)])

addInfoDict = {'track': ‘SD', ‘branch': “Smart”}

infoDict.update(addInfoDict)

#{'track': ‘SD', 'name': 'Ahmed', 'age': 17 , ‘branch': “Smart”}


Control
Flow
Conditions &
Loops
Control
If Flow
statement

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

languages = [‘JavaScript’, ‘Python’, ‘Java’]


for l in languages:
print(l)

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) # Starts at 0 and goes to 4: 0, 1, 2, 3, 4


range(2, 5) # Starts at 2 and goes to 4: 2, 3, 4
2.end (required):
•The sequence will stop before this value. It is the exclusive upper limit.

range(3, 10) # Produces: 3, 4, 5, 6, 7, 8, 9


3.step (optional):
•The difference between each number in the sequence. Defaults to 1.
•If a negative value is provided, the sequence will decrement.

range(0, 10, 2) # Produces: 0, 2, 4, 6, 8

range(10, 0, -2) # Produces: 10, 8, 6, 4, 2


Control
Range Flow
Function
Examples

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.

print(i) - It executes after the loop


completes its iterations normally
else: (i.e., it was not terminated by a
break statement).
print(10)

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 for i in range(10):


2
if (i == 5):
done
pass # Do nothing when i is 5
3

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

name = input(“What’s your Name? ”);


print(name);

Output:

What’s your name? Mahmoud


Mahmoud
Function
s
Make your code more
generic
Functio
Intr ns
o project.py
// Function definition
fnX

// Function calling
fnX()

fnX()
Functio
Definin ns
g
def fnName:
pass

Function

name Arguments Commands Return Values

def measureTemp ( temp ): def sum (x,y):


if temp < 37: res=x+y
print(res)
return “Too Cold”
elif temp > 37: sum(2,4) #6
return “Too Hot”
return “Normal”
measureTemp(37)
# “Normal”
Functio
Default ns
Arguments

def doSum(x, y = 2,z = 3):


sum = x + y + z
print(sum)

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

doSum(x = 2, y = 26) # output: 2


26
Scop
e your
To know
limits
Scope
• Variable's scope: is determined by where it is lexically
(textually) defined in the code.
• Variables defined in:
1. The global scope (outside all functions) are accessible
throughout the module.
2. The local scope (inside a function) are only accessible within
that function.
3. The enclosing scope (an outer function for a nested function) is
accessible to the inner function but not vice versa.
scope
x = 10 # Global scope
def outer():
x = 20 # Enclosing (non-local) scope
def inner():
x = 30 # Local scope
print(x) # Refers to the local 'x'
inner()
print(x) # Refers to the 'x' in the enclosing scope

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.

- They can be accessed and modified globally within the module.

- The global keyword allows you to modify these global variables inside functions.

EX:

global_var = 'I am global’ # global var


def access_global():
print(global_var) # Accessing a global variable inside a function

def modify_global():
global global_var
global_var = 'Modified global' # Modifying a global variable inside a function

access_global() # Output: I am global


modify_global()
access_global() # Output: Modified global
nonlocal Keyword: Used to modify variables in the nearest enclosing (non-global)
scope.

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”

outerFn() innerFn Scope

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() innerFn Scope

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() innerFn Scope

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

def outerFn(): nam


name = “Ahmed”
e
name = “Ali”
???
def innerFn():
print(name)
innerFn()
oute
rFn()
print(name)

Output:
Ali
Scop
Lexical e

Scope
name = “Ahmed” Global Scope

def outerFn(): nam


name = “Ahmed”
e
name = “Ali”
???
def innerFn():
print(name)
innerFn()
oute
rFn()
print(name)

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

def outerFn(): nam


name
name==“Ahmed”
“Ali”
e
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(): nam


name
name==“Ahmed”
“Ali”
e
global name
???
name = “Ali”
outerFn Scope
def innerFn():
print(name)
innerFn() innerFn Scope
outerFn()

Output:
Ali
Scop
global e

Keyword
name = “Ahmed” Global Scope

def outerFn(): nam


name
name==“Ahmed”
“Ali”
e
global name
???
name = “Ali”
def innerFn():
print(name)
innerFn()
outerFn()

Output:
Ali
Scop
global e

Keyword
name = “Ahmed” Global Scope

def outerFn(): nam


name
name==“Ahmed”
“Ali”
e
global name
???
name = “Ali”
def innerFn():
print(name)
innerFn()
oute
rFn()
print(name)
Output:
Ali

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”

name = “Sara” innerFn Scope


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”

name = “Sara” innerFn Scope


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”

name = “Sara” innerFn Scope


innerFn()
print(name)
outerFn()

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”

name = “Sara” innerFn Scope


innerFn()
print(name)
outerFn()

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”

name = “Sara” innerFn Scope


innerFn()
print(name)
outerFn()

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”

name = “Sara” innerFn Scope


innerFn()
print(name)
outerFn()

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”

name = “Sara” innerFn Scope


innerFn()
print(name)
outerFn()

Output:
Ali
Sara
Tips and
Tricks
Tips and
Shorthand Tricks
If

Do a command if this condition is true else do other command

Example

canFly = True
bird = “Dove” if canFly else “Penguin”

# output: bird = “Dove”


Tips and
Swap Tricks
Variables

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=".")

print("I", "love", "python")

Output:

I’m Ahmed. I Love Python


join and Tips and
Tricks
split

“:”.join([“1”,“Ali”,“grp”]) # colon is the separator


# ‘1:Ali:grp’
“ ”.join(“ITI”) # space is the separator
# ‘I T I’
“Sara # space is the
Mohamed”.split(
“ ”)
# [“Sara” , delimiter # colon is
“Mohamed”]
“django:flask”. the delimiter
split(“:”)
# [“django” ,
“flask”]
Tips and
is vs Tricks
==
 Use == (Equality operator) when you want to check if the values of two objects are
equal, regardless of whether they are the same object in memory.
 Use is (Identity operator) when you want to check if two references point to the exact
same object.
a = [1, 2, 3]
b = [1, 2, 3]
c=a
print(a == b) # True, because their values (contents) are the same
print(a is b) # False, because they are different objects in memory
print(a is c) # True, because `c` references the same object as `a`

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

enumerate(): Adds an index to each item in the iterable.

Useful: when you need to perform operations based on both the index (position) and the
value in a loop.

languages = [“JavaScript”, “Python”, “Java”]


for i , l in enumerate(languages):
print(“Element Value: ” , l, end=“, ”)
print(“Element Index: ” , i)

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

any(): check if one item at least in an iterable is truthy value.

Returns True if at least one element in the iterable is True. Otherwise,


returns False.
L = [0,5,9,7,8]
all(L) #False
any(L)

#True
Thank
You

You might also like