Python - All Lecs
Python - All Lecs
Fundamentals
Using Python
Romisaa Galal
COURSE OBJECTIVES
Behind every mouse click and touch-screen tap, there is a computer program that
makes things happen. This course introduces the fundamental building blocks of
programming and teaches you how to program using the Python language.
3
Python Inventor
Ahmed Moawad
Why Python
General Purpose
Language
Ahmed Moawad
HOW PYTHON WORKS
Noha Shehab 6
Python 2 or 3
Python 2 is the legacy, Python 3 is the future of the language
WHAT COMPUTERS DO?
Main Functions
Calculations Storage
8
9
SYNTAX
Noha Shehab 10
Syntax
Identifiers Rules
Ahmed Moawad
Syntax
Reserved Words
A Python identifier ’ be one of these words
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
Ahmed Moawad
Line Indentations Syntax
Level 1
Level 2
if True:
print(“Hello, World”)
else:
print(“Bye, World”)
No ;
Just Line Indentation
Ahmed Moawad
Quotes …1.. 2 ... 3 Syntax
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
Ahmed Moawad
Syntax
Comments
# this is a comment
Ahmed Moawad
PYTHON VARIABLES
● Python is loosely typed language.
● No need to define the variable, the interpreter will do everything.
● To define a variable
Name = ‘Romisaa’
Age = 25
Variable identifier Value
Noha Shehab 16
PYTHON VARIABLES
Variables
Local Global
Data Types
Primitive Non-Primitive
String Tuples
Integer Lists
Float Sets
Boolean Dictionaries
type(value)
18
TYPE CONVERSION
X = 20
print(type(X))
→ int
print(str(X))
→ str
19
Operators
Ahmed Moawad
Operators
Arithmetic
+ addition Op 2 + 3 #output: 5
- Subtraction Op 4 – 2 #output: 2
* Multiplication Op 4 * 5 #output: 20
% Modulus Op 16 % 5 #output: 1
** Exponent Op 2 ** 4 #output: 16
Ahmed Moawad
Operators
Assignment
= assign x = 4 #output: 4
Ahmed Moawad
Operators
Comparison
a <op> b
Ahmed Moawad
== Examples Comparison operators
True = 1, False = 0
Ahmed Moawad
Boolean Operators
Expression (Logic Gate) Expression
Ahmed Moawad
Logic Gates Boolean Operators
or OR Logic Gate
Ahmed Moawad
More Examples Boolean Operators
2 and 1 #output: 1
2 or 1 #output: 2
2 and 0 #output: 0
0 and 2 #output: 0
False or 0 #output: 0
Ahmed Moawad
FALSY VALUES
● None
● {}
● “”
● ()
● 0
● False
● Empty collections
Noha Shehab 28
Strings
Play with Strings
Ahmed Moawad
STRING
name = 'Noha'
● A string is a sequence of characters. work = "Information Technology
Institute"
print(work[2:8]) # ?
● Count chars print(work[-2]) # t
○ work.count("j")
print(work[100]) # ?
Noha Shehab 30
How To Strings
name = “Ahmed”
---or---
name = ‘Ali’
Ahmed Moawad
Play ! Strings
name = “Ahmed ”
print(name) # Ahmed
print(name[4]) # d
print(name[1:3]) # hm
print(name[:4]) # Ahme
Ahmed Moawad
Methods Strings
len(name) #32
order.replace(“info”, “”,2)
digits.isDigit() # True
containDigits.isDigit() # False
Ahmed Moawad
String Formatting Strings
str.format(*args,**kwargs)
Example
intro = “My Name is {0}”
intro.format(‘Ahmed’)
# My Name is Ahmed
Ahmed Moawad
STRING FUNCTIONS
# define a pattern
● Replace greet = "Welcome to your first python course
provided by @ " # replace certain parts with others
print(greet.replace("@", "iti"))
Noha Shehab 35
STRING FUNCTIONS
● isdigit: x = "10"
# check the value inside the string is digit
print(x.isdigit()) # True
Noha Shehab 37
Numbers
Play with Numbers
Ahmed Moawad
Types Numbers
int 18
long * 503340343L
float 18.5
complex
19+4j
Ahmed Moawad
Type Conversion Numbers
int int(“18”)
long(18.5)
long
float(15)
float
complex(4,5)
complex
Ahmed Moawad
Play ! Numbers
w, x, y, z = 4, 4.4, 4.6, 15
round(x) #output: 4
round(y) #output: 5
max(x,y,z) #output: 15
Ahmed Moawad
Data Structures
Ahmed Moawad
Data Structures
lists
Ahmed Moawad
DATA STRUCTURE
● Python has different datatypes like lists, sets, tuples and dictionaries.
Noha Shehab 44
LISTS [MUTABLE]
l = list([5, 6, 7])
print(l3)
● Lists can hold different lists also.
Noha Shehab 45
LISTS[MUTABLE]
● Lists are mutable data types, means that the values can be updated in
the run time. z = ["abc", 55, 67]
print(z[2])
z[2] = "updated item"
z[3] = "new item added"
● You can only update items at existing indices.
Noha Shehab 46
Intro Lists
newList = []
Ahmed Moawad
Methods Lists
myList myList.pop(4)
JavaScript
Python
Java
Ahmed Moawad
Methods Lists
myList myList.pop(4)
C myList.append(“go”)
JavaScript
Python
Java
go
Ahmed Moawad
Methods Lists
myList myList.pop(4)
C myList.append(“go”)
JavaScript
myList.insert(3, ‘Scala’)
Python
Scala
Java
go
Ahmed Moawad
Methods Lists
go
myList.remove(“C”)
Ahmed Moawad
Methods Lists
myList
JavaScript
• myList.pop(4) myList.append(“go”)
Python
myList.insert(3, ‘Scala’)
Scala
Java
myList.remove(“C”)
go
Rub
y
• yourList = [“Ruby”, “Rust”];
Rust
myList.extend(yourList)
Ahmed Moawad
Data Structures
Tuples
Immutable Lists
Ahmed Moawad
Intro Tuples
newTuple = ()
Ahmed Moawad
Data Structures
Dictionaries
Key/value Pairs
Ahmed Moawad
Intro Dictionaries
newDict = {}
Ahmed Moawad
Methods Dictionaries
infoDict.items()
infoDict.update(addInfoDict)
Ahmed Moawad
Control Flow
Conditions & Loops
Ahmed Moawad
If statement Control Flow
if (x == 2):
print(“Two”)
elif (x == 3):
print(“Three”)
else:
print(“others”)
Ahmed Moawad
for …in Control Flow
Output:
JavaScript
Python
Java
Ahmed Moawad
Range Function Control Flow
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]
for i in range(10):
print(i)
0 1 2 3 4 5 6 7 8 9
Ahmed Moawad
while Control Flow
dayCount = 0
while dayCount < 4:
print(“We are learning Python”)
dayCount += 1
Output: DayCount
We are learning Python 1
We are learning Python 2
We are learning Python 3
We are learning Python 4
Ahmed Moawad
Break Statement Control Flow
for i in range(10):
if (i == 5):
break
print(i)
0 1 2 3 4
Ahmed Moawad
Continue Statement Control Flow
for i in range(10):
if (i == 5):
continue
print(i)
0 1 2 3 4 6 7 8 9
Ahmed Moawad
Else Statement Control Flow
for i in range(10):
if (i == 5):
continue
print(i)
else:
print(10)
0 1 2 3 4 6 7 8 9 10
Ahmed Moawad
input Function Python I/O
input(prompt_message)
Example
Output:
Ahmed Moawad
OOP
67
Object Oriented Python
Intro OO Python
Modules
Object Oriented
Functions Level
Modular Level
Procedural
Level
Speghatti Level
walk() stop()
speak() Methods move()
ride( BikeObj )
OOP Keywords
Class OOP Keywords
man = Human()
Man Object
man = Human()
Output:
Hi there
Man Object
self.name = name
init ()
man = Human(“Ahmed”)
Name is Ahmed
Man Object
man = Human(“Ahmed”)
init ()
man2 = Human(“Mohamed”)
My Name is Ahmed
cls.faults +=1
makeFaults()
print(cls.faults)
Human.makeFaults() #1
man = Human(“Ahmed”)
man.makeFaults() #2
Static Method isa normal function that have logic that related to the Class
init ()
@staticmethod
def measureTemp(temp):
if (temp == 37): measureTemp()
return “Normal”
return “Not Normal”
class Human:
class Human:
@classmethod @staticmethod
def walk(cls): def sleep():
print(“Walk …”) print(“whoa”)
Human.walk() Human.sleep()
OOP Concepts
OOPConcepts
Inheritance
Intr Inheritance
o
Human
Class
Employee
Class
Engineer Teacher
Class Class
class Human:
def init (self, name):
self.name = name
Human Class
def speak(self):
print(“My Name is ”+self.name);
class Employee(Human):
def init (self, name, salary):
super(Employee, self). init (name)
self.salary = salary
def work(self):
print(“I’m working now”);
emp = Employee(“Ahmed”, 500) Employee
emp.speak()
Class
emp.work()
Open Source Department – ITI
Multiple Inheritance
Inheritance
Python supports Multiple Inheritance
Report**:
Human Mammal
1- How super Function handle Multiple Inheritance.
Class Class
2- If Human and Mammal Have the same method
Polymorphism
Intr Polymorphism
o
Poly means "many" and morphismmeans "forms". Different classes might define
the same method or property.
Fly()
Report**:
Can we do overloading in Python ?
Encapsulation
intr Encapsulation
o
Encapsulation is the packing of data and functions into one component (for
example, a class) and then controlling access to that component .
getName()
Class
amigos
class Human:
def init (self, name):
self. name = name
def getName(self):
return self. name
man = Human(“Mahmoud”)
print(man. name)
print(man.getName())
#output: Mahmoud
106