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

Python - All Lecs

This document provides an introduction to programming fundamentals using the Python language. It covers course objectives, why Python is a good choice, how Python works, syntax rules for identifiers, reserved words, comments, variables, data types, type conversion, operators including arithmetic, assignment, comparison, boolean, and strings. The objectives are to teach the basic building blocks of programming using Python with no prerequisites required. Python is presented as an easy to learn, general purpose language suitable for rapid development.

Uploaded by

yasmiinhassan33
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 views

Python - All Lecs

This document provides an introduction to programming fundamentals using the Python language. It covers course objectives, why Python is a good choice, how Python works, syntax rules for identifiers, reserved words, comments, variables, data types, type conversion, operators including arithmetic, assignment, comparison, boolean, and strings. The objectives are to teach the basic building blocks of programming using Python with no prerequisites required. Python is presented as an easy to learn, general purpose language suitable for rapid development.

Uploaded by

yasmiinhassan33
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/ 93

Programming

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.

No prerequisite knowledge is needed.

3
Python Inventor

guido van rossum

Ahmed Moawad
Why Python

Easy To learn Rapid Development

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

● Download the python interpreter


○ https://www.python.org/downloads/windows/

● Your first Hello world.

Noha Shehab 10
Syntax
Identifiers Rules

A Python identifier is a name used to identify a variable, function, class,


module or other object

Starts only with: a→z A→Z _

Can’t Contain : Punctuations Characters

Can C ontain: digits a→z A→Z _

Python is Case Sensitive Language

Ahmed Moawad
Syntax
Reserved Words
A Python identifier ’ 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

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

Def x(): Name = ‘Ahmed’


Name = ‘Romisaa’ Def x():
Print(Name) Print(Name)
x() x()
17
DATA TYPES

Data Types

Primitive Non-Primitive

String Tuples

Integer Lists

Float Sets

Boolean Dictionaries

type(value)
18
TYPE CONVERSION

The process of converting a data type into another data type.

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

/ Division Op 16 / 5 #output: 3.2

% Modulus Op 16 % 5 #output: 1

// Division without Fractions 16 // 5 #output: 3

** Exponent Op 2 ** 4 #output: 16

Ahmed Moawad
Operators
Assignment

= assign x = 4 #output: 4

+= 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 assign x %= 8 #output: 7

//= floor divide and assign x //= 3 #output: 2

**= get exponent and assign x **= 4 #output: 16

Ahmed Moawad
Operators
Comparison

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 True if a not equals b

<> return True if a not equals b

> return True if a greater than b

< return True if a lesser than b

Ahmed Moawad
== Examples Comparison operators

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

Ahmed Moawad
Boolean Operators
Expression (Logic Gate) Expression

Ahmed Moawad
Logic Gates Boolean Operators

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

Ahmed Moawad
More Examples Boolean Operators

2 and 1 #output: 1

2 or 1 #output: 2

not 4 #output: False

not 0 #output: True

2 and 0 #output: 0

0 and 2 #output: 0

“Google” and 1 #output: 1

“” and “Go” #output: “”

False or 0 #output: 0

Ahmed Moawad
FALSY VALUES

● Falsy values are values that evaluate to False in a boolean context.


● Falsy values include empty sequences (lists, tuples, strings, dictionaries, sets),
zero in every numeric type, None , and False.

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

● String is treated like an array


● access string part according index starts from 0

● You can calculate its length. print(len(name)) # 4

● Access certain char at some position. print(work[10]) # n

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

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

print(name[4]) # d

print(name[1:3]) # hm

print(name[:4]) # Ahme

print(name[6]) # Index Error

Ahmed Moawad
Methods Strings

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

digits,containDigits = “0102002932”, “Tel0102002932”

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

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


intro.format(name=‘Ahmed’, place=‘ITI’)
# My Name is Ahmed, I work at ITI

Ahmed Moawad
STRING FUNCTIONS

● Capitalize x = "people develop countries, we develop people"


print(x.capitalize())

OUTPUT: People develop countries, we develop people

# 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

name, email = "noha", "[email protected]"


● isalpha: # #is_alpha
# check all symbols value inside the string are characters
print(email.isalpha())
● isnumeric: # is_numeric
print(name.isnumeric())

● Check capital or small name = "itI"


# ---> islower ---> conver .lower()
print(name.islower())

https://docs.python.org/3/library/string.html# Noha Shehab 36


STRING FUNCTIONS
# string strip
● Strip, lstrip , rstrip: # string.strip , lstrip , rstrip
greet = " " to day02
welcome
print(len(greet))
greet = greet.rstrip()
print(len(greet))

● Format string student = "Zeniab"


# format string mytemp = f"Good morning {student}"
name = "Noha"
faculty = "Engineering"
greet = "My name is {0} I graduated from faculty of {1}" # create common format
print(greet.format(name, faculty))
greet = "My name is {n} I graduated from faculty of {f}" # create common format
print(greet.format(f=faculty, n=name))

Noha Shehab 37
Numbers
Play with Numbers

Ahmed Moawad
Types Numbers

int 18

long * 503340343L

float 18.5

complex
19+4j

* Available in Python 2 only

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

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

max(x,y,z) #output: 15

Ahmed Moawad
Data Structures

Ahmed Moawad
Data Structures

lists

Ahmed Moawad
DATA STRUCTURE

● The most basic data structure in python is called sequence.

● A sequence, collection of elements, each element is assigned to a


number, starts form 0 , represent its position or index.

● Python has different datatypes like lists, sets, tuples and dictionaries.

● Most common sequences are lists and tuples.

Noha Shehab 44
LISTS [MUTABLE]

● Lists: the versatile datatype available in python.


● A collection of various data types. l = []

● To define a list: l = list([5, 6, 7])


l2 = ["iti", "3DFX", "python", "databases"]

● Lists can hold different values, with different datatypes.

l = list([5, 6, 7])

l3 = ["a", 5, "test", True, l]

print(l3)
● Lists can hold different lists also.

Noha Shehab 45
LISTS[MUTABLE]

● Get items at certain index: z = ["abc", 55, 67]


print(z[2])

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

● You can sort the list items.

organic = ['kiwi', 'orange', 'apple', 'tomato', 'Carrot']


organic.sort() # sort ascending
organic.reverse() # sort descending

Noha Shehab 46
Intro Lists

A collection of various data types

newList = []

newList = [1, “hi”, True]


newList[0] #1
newList[1] #”Hi”
newList[2] #True
newList[3] #Index Error

Ahmed Moawad
Methods Lists

myList = [“C”, “JavaScript”, “Python”, “Java”, “php”];

myList myList.pop(4)

JavaScript

Python

Java

Ahmed Moawad
Methods Lists

myList = [“C”, “JavaScript”, “Python”, “Java”, “php”];

myList myList.pop(4)

C myList.append(“go”)
JavaScript

Python

Java

go

Ahmed Moawad
Methods Lists

myList = [“C”, “JavaScript”, “Python”, “Java”, “php”];

myList myList.pop(4)

C myList.append(“go”)
JavaScript
myList.insert(3, ‘Scala’)
Python

Scala

Java

go

Ahmed Moawad
Methods Lists

• myList = [“C”, “JavaScript”, “Python”, “Java”, “php”];


myList

JavaScript • myList.pop(4) myList.append(“go”)


Python

Scala myList.insert(3, ‘Scala’)


Java

go
myList.remove(“C”)

Ahmed Moawad
Methods Lists

• myList = [“C”, “JavaScript”, “Python”, “Java”, “php”];

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

Same as Lists but Tuples are immutable

newTuple = ()

t = (1, “hi”, True)


t[1]
# hi
t[1] = 4
TypeError: 'tuple' object does not support item assignment

Ahmed Moawad
Data Structures

Dictionaries
Key/value Pairs

Ahmed Moawad
Intro Dictionaries

A key: value comma seperated elements Data Structure

newDict = {}

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


d[“name”]
# Ahmed
d[“name”] = “Ali”
# {name: “Ali”, track: “OS”}

Ahmed Moawad
Methods Dictionaries

infoDict = {'track': 'OS', 'name': 'Ahmed', 'age': 17}

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

‘name’ in infoDict # True

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

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

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


for l in languages:
print(l)

Output:
JavaScript
Python
Java

Ahmed Moawad
Range Function Control Flow

range([start,] end[, step])

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

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


print(name);

Output:

What’s your name? Mahmoud


Mahmoud

Ahmed Moawad
OOP

67
Object Oriented Python
Intro OO Python

Modules

Object Oriented
Functions Level

Modular Level
Procedural
Level
Speghatti Level

Open Source Department – ITI


OO Python
Intro

height = 175 cm velocity = 200 m/s


weight = 76 kg Properties brakes = 2

walk() stop()
speak() Methods move()

ride( BikeObj )

Man Object Bike Object

Open Source Department – ITI


OO Python

OOP Keywords
Class OOP Keywords

A class is a template definition of an object's properties and methods.

class Human: Human Class


pass

Open Source Department – ITI


Object OOP Keywords

An Object is an instance on a Class.

class Human: Human Class


pass

man = Human()

Man Object

Open Source Department – ITI


Constructo OOP Keywords
r
Constructoris a method called at the moment an object is instantiated.

class Human: Human Class

def init (self):


print(“Hi there”) init ()

man = Human()

Output:

Hi there
Man Object

Open Source Department – ITI


Instance Variable OOP Keywords

Instance Variable is an object characteristic, such as name.

class Human: Human Class

def init (self, name): name

self.name = name
init ()

man = Human(“Ahmed”)

Name is Ahmed

Man Object

Open Source Department – ITI


Class Variable OOP Keywords

ClassVariable is the variable that shared by all instances.

class Human: Human Class


makeFault = True makeFault = True

def init (self, name): name


self.name = name;

man = Human(“Ahmed”)
init ()
man2 = Human(“Mohamed”)

Name is Ahmed Name is Mohamed

He makes faults He makes faults

Open Source Department – ITI


Class Variable OOP Keywords

class Human: Output:


faults = 0
def init (self, name):
self.name = name; Man : 1

man = Human(“Ahmed”) Man2 : 0


man2 = Human(“Mohamed”)
Human : 0
man.faults = 1
Man2 : 2
print("Man :", man.faults)
print("Man 2:", man2.faults) Human : 2
print("Human:", Human.faults)
Man : 1
Human.faults = 2
print("Man 2:", man2.faults)
print("Human:", Human.faults)
print("Man :", man.faults)

Open Source Department – ITI


Instance Method OOP Keywords

Instance Method is an object capability, such as walk.

class Human: Human Class


def init (self, name):
self.name = name
name
def speak(self):
print(“My Name is ”+self.name)
init ()
man = Human(“Ahmed”)
man.speak() speak()

My Name is Ahmed

Open Source Department – ITI


Class Method OOP Keywords

ClassMethod is a method that shared by all instances of the Class

class Human: Human Class


faults=0
faults
def init (self, name):
self.name = name name
@classmethod
def makeFaults(cls): init ()

cls.faults +=1
makeFaults()
print(cls.faults)
Human.makeFaults() #1
man = Human(“Ahmed”)
man.makeFaults() #2

Open Source Department – ITI


Static Method OOP Keywords

Static Method isa normal function that have logic that related to the Class

class Human: Human Class


def init (self, name):
name
self.name = name

init ()
@staticmethod
def measureTemp(temp):
if (temp == 37): measureTemp()

return “Normal”
return “Not Normal”

Human.measureTemp(38) # Not Normal

Open Source Department – ITI


OOP Keywords
Static vs Class Methods

Class Method Static Method


# cls(Class) is implicity # Static Method is like a
passed to class method like normal function but we put it
self(instance) in instance in the class because it have
method. logic that related to the
class.
# Class Method is related
to the class itself. # We call it Helper Method

class Human:
class Human:
@classmethod @staticmethod
def walk(cls): def sleep():
print(“Walk …”) print(“whoa”)

Human.walk() Human.sleep()

Open Source Department – ITI


OO Python

OOP Concepts
OOPConcepts

Inheritance
Intr Inheritance
o
Human
Class

Employee
Class

Engineer Teacher
Class Class

Open Source Department – ITI


Example Inheritance

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

like eat but with different Implementation. When

Child [Employee] calls eat method how python

Employee handle this case.


Class

**Prove your opinion with examples.

Open Source Department – ITI


OOPConcepts

Polymorphism
Intr Polymorphism
o
Poly means "many" and morphismmeans "forms". Different classes might define
the same method or property.

Eagle Fly() Ifly very fast

Bird class Dove Fly() Ifly for long distanc es

Fly()

Ifly ☺ Penguin Fly() Ica n’t fly 

Open Source Department – ITI


Method Polymorphism
Overriding
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 speak(self):
print(“My salary is ”+self.salary);
Employee
emp = Employee(“Ahmed”, 500)
Class
emp.speak() #My Salary is 500

Open Source Department – ITI


Method Overloading Polymorphism

Report**:
Can we do overloading in Python ?

If Yes, Tell me How??

If No, Tell me Why??

* * Support YourAnswer by Examples.

Open Source Department – ITI


OOPConcepts

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

Open Source Department – ITI


Example Encapsulation

class Human:
def init (self, name):
self. name = name
def getName(self):
return self. name

man = Human(“Mahmoud”)
print(man. name)

AttributeError: 'Human' object has no attribute ‘ name’

print(man.getName())
#output: Mahmoud

Open Source Department – ITI


TIME TO
PRACTICE

106

You might also like