You are on page 1of 16

String

“string”.title() :1st litter is capital , note : title() and other () come after “.”,is method
“string”.upper() : all litters is capital
“string”.lower() : all litters is small
F” sring {string} {string} string” : called f-string method , earlier method was (var=”{}
{}”.format (1st string, 2nd string,…))
“\n” : add new line to text
“\t” : add tab to text
“\n\t” : move to a new line, and start the next line with a tab
“string”.strip() : to eliminate the whitespace before & after string, .rstrip() for right
whitespace & .lstrip() for left whitespace

Number :
Note : you can writing long numbers in Python prog. using underscores to make large
numbers more readable ‘universe_age = 14_000_000_000’ when you print,
python will prints only the digits : 14000000000

Note : divide int number. on int number will give float number

Multiple assignment : x,y,z =0,0,0

List :
list name(lstn)=[‘string’,’string’,…’last’] : In Python, square brackets( [ ] )indicate a list
lstn[index] : access any element in a list by telling Python the position, or index, of
the item desired. 1st item in list has index 0 and cont. , also may use last item
index from -1 ,-2,… to 1st item
lstn[index].method : you can use same method above in string as title() , upper(),
lower() , …
Note : to print all list item, print(lstn) _ to print individual item in list, print(lstn[index])
lstn[index]=’string’ : to change an element in list with same index
1
lstn.append(‘string’) : to add new element at the end of list
lstn=[ ] : to create new empty list
lstn.inser(index,‘string’) : to add a new element at any position in list
del lstn[index] : to remove an item or a set of items from a list.
lstn.pop() : to removes the last item in a list and isolate the removed item in pop()
lstn.pop(index) : to remove an item from any position in a list and isolate the
removed item in pop(index)
lstn.remove(“string”) : to remove an item by value
Note : The remove() method deletes only the first occurrence of the value you specify. If there’s
a possibility the value appears more than once in the list, you’ll need to use a loop
to make sure all occurrences of the value are removed

lstn.sort() : to sort a list alphabetical permanently


lstn.sort(reverse=True) : to sort a list permanently in reverse alphabetical (from Z to A)
sorted(lstn) : to sort a list temporarily
sorted(lstn,reverse=True) : to sort a list temporarily
lstn.reverse() : To reverse the original order of a list
len(lstn) : to get the length of list (no. of element in list)
rule : to read all items in list, must doing loop: this known as “for item in list_of_items:”
for item in lstn: # read from list ‘listn’
print (item) # printing

Making Numerical Lists:

Method1: Using the range() Function , ex


for value in range(1, 5) # 5 not include in value range
print(value)
result : 1,2,3,4 (vertically)

Method2: Using range() to Make a List of Numbers , lstn=lsit(range(1st number ,last


number, increment)

2
Ex1 :
numbers = list(range(1, 6))
print(numbers)
result : [1, 2, 3, 4, 5]
Ex2 :

squares = []
for value in range(1, 11):
square = value ** 2
squares.append(square)
print(squares)
result : [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Ex3 : List comprehension (give same result of above ex but in few lines)

squares = [value**2 for value in range(1, 11)]


print(squares)

Some of Simple Statistics with a List of Numbers :

min(lstn) : give min value in list


max(lstn) : give max value in list
sum(lstn) : give sum of list values

Working with Part of a List:


* Slicing a List : ex -
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])
res : ['charles', 'martina', 'michael']
note : -Without a starting index, Python starts at the beginning of the list
players[0:3] = players[ :3]
-Without ending index, Python return all items from stating index to end of the
list players[1: ] = players[1:3]
* Looping Through a Slice : ex-
players = ['charles', 'martina', 'michael', 'florence', 'eli']
for player in players[:3]:
print(player.title())
res : Charles
Martina
Michael
* Copying a List , by using [ : ]

my_foods = ['pizza', 'falafel', 'carrot cake']


3
friend_foods = my_foods[:]
print(my_foods)
print(friend_foods)
res : ['pizza', 'falafel', 'carrot cake']
['pizza', 'falafel', 'carrot cake']

Tuples : Python refers to values that cannot change as immutable, and an


immutable list is called a tuple. A tuple looks just like a list except you use
parentheses ( ) instead of square brackets ,EX –
dimensions = (200, 50)
print(dimensions[0]) , res : 200

* Looping Through All Values in a Tuple :


dimensions = (200, 50)
for dimension in dimensions:
print(dimension) res : 200 , 50

* Writing over a Tuple :


dimensions = (200, 50)
dimensions = (400, 100)
for dimension in dimensions:
print(dimension) res : 400 , 100

Note : car = 'Audi'


car == 'audi', False
to Ignore the Case When Checking for Equality :
car = 'Audi'
car.lower() == 'audi', True

Dictionaries : A dictionary in Python is a collection of key-value pairs. Each key is connected


to a value, and you can use a key to access the value associated with that key.

alien = {'color': 'green', 'points': 5}


print(alien ['color'])
print(alien ['points'])---} green , 5

 Adding New Key-Value Pairs


alien= {'color': 'green', 'points': 5}
print(alien_0)
alien['x_position'] = 0
alien['y_position'] = 25

4
print(alien) ---} {'color': 'green', 'points': 5}
{'color': 'green', 'points': 5, 'y_position': 25, 'x_position': 0}

 Starting with an Empty Dictionary


alien= { }

 Modifying Values in a Dictionary


alien= {'color': 'green'}
alien ['color'] = 'yellow'
print(alien) ---} {'color': 'yellow'}
 Removing Key-Value Pairs
alien= {'color': 'green', 'points': 5}
del alien ['points']
print(alien) ---} {'color': 'green'}

Note : you can write dictionary in multiline : { ……


……}
 Using get() to Access Values
you can use the get( ) method to set a default value that will be returned if the requested
key doesn’t exist
alien={'color': 'green', 'speed': 'slow'}
value = alien.get('points', 'No point value assigned.')
print(value) ---} No point value assigned.

 Looping Through a Dictionary


a- Looping Through All Key-Value Pairs, by using dictionary.items()
dic={'nazar':1975,'amjad':1976,"hatam":1984,'ahmed':1986 }
for k,v in dic.items() :
print(f"{k.tilte()} : {v.title()}")

b- Looping Through All the Keys in a Dictionary,by using dictionary.keys()


for k in dic.keys() :print(k)
c- Looping Through a Dictionary’s Keys in a Particular Order
for k in sorted(dic.keys()) :print(k)
d- Looping Through All Values in a Dictionary
for v in dic.values() : print(v)
Note to pull out the unique items in list that contains duplicate items we use set()
for v in set(dic.values())
 Nesting :
a- A List of Dictionaries
prog result

5
alien_0 = {'color': 'green', 'points': 5} {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10} {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15} {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
for x in aliens:
print(x)
lst=[] {'speed': 'slow', 'color': 'green', 'points': 5}
# Make 30 green lst. {'speed': 'slow', 'color': 'green', 'points': 5}
for i in range(30): {'speed': 'slow', 'color': 'green', 'points': 5}
dic = {'color': 'green', 'points': 5, {'speed': 'slow', 'color': 'green', 'points': 5}
'speed':'slow'} {'speed': 'slow', 'color': 'green', 'points': 5}
lst.append(dic)
# Show the first 5 lst
for i in lst[ : 5]:
print(i)
b- A List in a Dictionary
dic={ language : python
'jen': ['python', 'ruby'], language : ruby
'sarah': ['c'],
'edward': ['ruby', 'go'],
'phil': ['python', 'haskell'],
}
for k in dic['jen']:
print(f" language : {k}")

dic={ name : jen


'jen': ['python', 'ruby'], language is : python
'sarah': ['c'], language is : ruby
'edward': ['ruby', 'go'], name : sarah
language is : c
'phil': ['python', 'haskell'],
name : edward
} language is : ruby
for k,v in dic.items(): language is : go
print(f" name : {k}") name : phil
for i in v : language is : python
print(f"language is : {i}") language is : haskell
c- A Dictionary in a Dictionary
family={"nazar":{"first":'abody' , family name : nazar
'second':"sohaib"},'amar':{'first':"yosif", his sons : abody & sohaib
'second':"aos"}} family name : amar
his sons : yosif & aos
for name,son in family.items():
print(f 'family name : {name}')
hson=f '{son["first"]} & {son["second"]}'
print(f 'his sons : {hson}')

User Input and while Loops


* Sometimes you’ll want to write a prompt that’s longer than one line , ex.
prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name? "

6
name = input(prompt)
print(f"\nHello, {name}!")
---} If you tell us who you are, we can personalize the messages you see.
What is your first name? Eric
Hello, Eric!
 While Loop :
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1 ---} 1,2,3,4,5

 Letting the User Choose When to Quit


1- By using certain quit value
prompt="\n enter quit to exit from program ... !"
prompt +="\n What's your name :"
message =""
while message != 'quit' :
message = input(prompt)
if message != 'quit':
print(f"Hello Mr : { message }")

2- By using Flag : used for many different events could cause the program to stop running.
prompt="\n enter quit to exit from program ... !"
prompt +="\n What's your name :"
message =""
active = True
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
print(f"Hello Mr : { message }")

3- Using break to Exit a Loop : To exit a while loop immediately without running any remaining
code in the loop
prompt="\n enter quit to exit from program ... !"
prompt +="\n What's your name :"
active = True
while active:
message = input(prompt)
if message == 'quit':
break
else:
print(f"Hello Mr : { message }")

 Using continue in a Loop


current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number) ---} 1 3579

 Using a while Loop with Lists and Dictionaries


a- Moving Items from One List to Another
7
lst=['green','yellow','red','blue']
new_lst=[]
while lst :
color=lst.pop()
print(f"removed color : {color} ")
new_lst.append(color)
print(f"the new list created :{new_lst}")---} removed color : blue
removed color : red
removed color : yellow
removed color : green
the new list created :['blue', 'red',
'yellow', 'green']

b- Removing All Instances of Specific Values from a List


lst=['green','yellow','red','blue','yellow']
while "yellow" in lst :
lst.remove('yellow')
print(f"the new list created after remove yellow :{lst}")
---} the new list created after remove yellow : ['green', 'red', 'blue']

c- Filling a Dictionary with User Input


dict={}
active=True
while active :
fruit_name=input("\nwhat's your favorite fruit : ")
color=input("\nIt's color is :")
dict[fruit_name]=color
repeat=input("\n Do you want continue (y/n) :")
if repeat=="n" :
active=False
print(dict)
for fruit_name,color in dict.items() :
print(f"The {fruit_name} its color : {color}")

---} {'apple': 'red', 'grape': 'black'}


The apple its color : red
The grape its color : black

Functions parameter
def greet_user(username):
print(f"Hello, {username.title()}!")

greet_user('jesse') - calling
argument

 Equivalent Function Calls


def fdata(name,birthday=1980) :
print(f'your name is : {name} and birthday is : {birthday}')

fdata("nazar") your name is : nazar and birthday is : 1980


fdata(name="nazar")
fdata(name='nazar',birthday=1975) your name is : nazar and birthday is : 1980
fdata(birthday=1975,name='nazar') your name is : nazar and birthday is : 1975
fdata("nazar",1975) your name is : nazar and birthday is : 1975
your name is : nazar and birthday is : 1975
8
 Keyword Arguments : is a name-value pair that you pass to a function ,in the above the
keyword arguments are : birthday=1975,name='nazar'
 Return Values
def get_name(firstn,lastn):
full_name=f"\n{firstn} {lastn}"
return full_name
vname=get_name("nazar","hussein")
print(vname)

 Making an Argument Optional


def get_name(firstn,lastn,midname=""):
if midname:
full_name=f"\n{firstn} {midname} {lastn}"
else:
full_name = f"\n{firstn} {lastn}"
return full_name
vname=get_name("nazar","hussein")
print(vname) ---} nazar hussein
vname=get_name("nazar","hussein","abdulkareem")
print(vname) ---} nazar abdulkareem hussein

 Returning a Dictionary
def get_name(firstn,lastn):
full_name={'first':firstn,"last":lastn}
return full_name
vname=get_name("nazar","hussein")
print(vname) ---} {'first': 'nazar', 'last': 'hussein'}

 Passing a List
def fname(name):
for itr in name: ---} Hello aa
print(f" Hello {itr}") Hello bb
lst=['aa','bb','cc'] Hello cc
fname(lst)

 Modifying a List in a Function : in this method the original list will be empty
oldlst=['aa','bb','cc','dd']
newlst=[]
def fname(oldlst,newlst):
while oldlst :
name=oldlst.pop()
newlst.append(name)
return newlst
fname(oldlst,newlst)
print(newlst) ---} ['dd', 'cc', 'bb', 'aa']

 Preventing a Function from Modifying a List :in the above method the modified will empty
the original list, You can send a copy of a list to a function like this: function_name(original
list_name[:]) , in the above ex. : fname(oldlst[:],newlst

9
 Passing an Arbitrary Number of Arguments : Python allows a function to collect an arbitrary
number of arguments from the calling statement by : *parameter_name or the generic
parameter name *args

def fname(*parmt):
for itr in parmt: Hello : nazar
print(f"Hello : {itr}") ---} Hello : aa
fname(("nazar"))
fname("aa","bb",'cc') Hello : bb
Hello : cc
 Mixing Positional and Arbitrary Arguments
this year is 2022
def fname(yr,*parmt): Hello : nazar
print(f"\nthis year is {yr}")
for itr in parmt: ---}
print(f"Hello : {itr}") this year is 2020
fname(2022,"nazar") Hello : aa
fname(2020,"aa","bb",'cc') Hello : bb
Hello : cc
Using Arbitrary Keyword Arguments : you can write functions that accept as many key-value pairs
as the calling statement provides.The double asterisks before the parameter **dict cause Python to
create an empty dictionary called user_info and pack whatever name-value pairs it receives into this
dictionary. You’ll often see the parameter name **kwargs used to collect non-specific keyword
arguments.

def fname(first,last,**dict):
dict["first_name "]=first
dict["last_name "]=last
return dict
full_name=fname('nazar','hussein',birthday=1975,job="engineer")
print(full_name)

---} {'birthday': 1975, 'job': 'engineer', 'first_name ': 'nazar', 'last_name ': 'hussein'}

Storing Your Functions in Modules : You can storing your functions in a separate file called a
module and then importing that module into your main program. A module is a file
ending in .py that contains the code you want to import into your Functions program.

1- Importing an Entire Module : use the statement : import module_name


and to use the function of this module in the main programs we use the statement :
module_name.function_name( )
File : food.py
def pizza(size,*args):
print(f"the size of pizaa is {size} inch with following toppings : ")
for itr in args:
print(f"- {itr}")

main programs :
import food
food.pizza(16,'mushroom','extra cheese','green peppers')
food.pizza(12,'meat')

10
2- Importing Specific Functions : You can also import a specific function from a module. Here’s
the general syntax for this approach: from module_name import function_name
Also you can import as many functions as you want from a module by separating each function’s
name with a comma:
from module_name import function_0, function_1, function_2
and to use the function of this module in the main programs we use the statement :
function_name(arguments )
main programs :
from food import pizza
pizza(16,'mushroom','extra cheese','green peppers')
pizza(12,'meat')

3- Using as to Give a Function an Alias


If the name of a function you’re importing might conflict with an existing name in your program
or if the function name is long, you can use a short, unique alias—an alternate name similar to a
nickname for the function. The general syntax for providing an alias is:
from module_name import function_name as fn
main programs :
from food import pizza as mp
mp(16,'mushroom','extra cheese','green peppers')
mp(12,'meat')

4- Using as to Give a Module an Alias :- The general syntax for this approach is:
import module_name as mn
main programs :
import food as p
p.pizza(16,'mushroom','extra cheese','green peppers')
p.pizza(12,'meat')

Importing All Functions in a Module :- You can tell Python to import every function in a module by
using the asterisk (*) operator : from module_name import *

Classes :
Method : It is functions in the class.
Attribute : It is variable in the class.
Instance : It is Object made from class.
To Create Object(calling Glass) : Object_name=Class_name(arguments )
To call a method : Instance_Name.method( ) (( dot syntax))
To access to Attribute : Instance_Name.Attribute
11
global attribute : is an attribute is declared inside of a class, but not within the init method and can be
referenced by the class directly.
instance attributes : Any attributes declared within the init method using the self keyword and can only
be accessed by the class instances
self required to access attributes defined in the class

# using and accessing global class attributes


class Car ():
sound = "beep" # global attribute, accessible through the class itself
def __init__(self, color):
self.color = "blue" ‘’’ instance specific attribute, not accessible through the class itself ’’’
print(Car.sound)
#print(Car.color) won't work, as color is only available to instances of the Car class, not the class
itself
ford = Car("blue")
print(ford.sound, ford.color) # color will work as this is an instance

class Car:
def __init__(self,model,make,year):
self.model=model
self.make=make Attributes (variables)
self.year=year
def spc(self):
full_det=f"{self.make}:{self.model} - {self.year}" Methods(Functions)
return full_det
car_det=Car("Camry","Toyota",2008) - Object
print(car_det.spc()) - Instance

Res -  Toyota : Camry – 2008

# using the self keyword to access attributes within class methods


class Dog( ):
sound = "bark"
def makeSound(self):
print(self.sound) # self required to access attributes defined in the class
sam = Dog( )
sam.makeSound()

# understanding which methods are accessible via the class itself and class instances
class Dog( ):
sound = "bark"
def makeSound(self):
print(self.sound)
def printInfo( ):
print("I am a dog.")
Dog.printInfo( ) # able to run printInfo method because it does not include self parameter
# Dog.makeSound( ) would produce error, self is in reference to instances only
sam = Dog( )
sam.makeSound( ) # able to access, self can reference the instance of sam
# sam.printInfo( ) will produce error, instances require the self parameter to access methods

--------------------------------------
12
We’ve defined two methods within our Dog class this time. One method has self within the parameter, while the
other does not. The method without the self parameter can be accessed through the class itself, which is why
line 8 outputs “I am a dog.”. The 9th line is commented out because makeSound can only be accessed by
instances of our Dog class, not the class itself. Lastly, we can see that the 12th line is also commented out
because methods that are not defined with self as a parameter cannot be accessed by instances of the class.
Otherwise, we would produce an error. This is the importance of the self keyword.

 Setting a Default Value for an Attribute


When an instance is created, attributes can be defined without being passed in as parameters.
These attributes can be defined in the __init__( )method, where they are assigned a default value.

Ex. :
Class Car
………… (same above ex.)
self.odometer=0 (inside def __init__)
def read(self):
print(f"This car odometer reading : {self.odometer}")
car_det.read()

---- Toyota : Camry - 2008


This car odometer reading : 0

 Modifying Attribute Values


1- Modifying an Attribute’s Value Directly : The simplest
way to modify the value of an attribute is to
access the attribute directly through an instance. By adding the following lines in the above ex.
car_det.odometer=2000 (calling attribute)
car_det.read() (calling method)

2- Modifying an Attribute’s Value Through a Method : By using new method to update the certain
attribute

def update(self,milage):
self.odometer=milage new method

car_det.update(5000)
car_det.read()

3- Incrementing an Attribute’s Value Through a Method :

def update(self,milage):
self.odometer=milage
def incr(self,mile):
self.odometer+=mile

car_det.update(5000)
car_det.read()
car_det.incr(300)
car_det.read()

13
Inheritance
When one class inherits from another, it takes on the attributes and methods of the first class
- The original class is called the parent class
- the new class is the child class
- The super( ) method is a special function to call a method from the parent class
- The syntax of inheritance : child class(parent class)
Ex.

# inheriting a class and accessing the inherited method


class Animal():
def makesound(self):
print('roar')

class Dog(Animal): # inheriting Animal class


species='Canine'

sam=Dog()
sam.makesound() # accessible through inheritance
lion=Animal()
# lion.species not accessible, inheritance does not work backwards

 Using the super( ) Method


# using the super( ) method to declare inherited attributes
class Animal():
def __init__(self,species):
self.sp=species
class Dog(Animal):
def __init__(self,species,name):
self.nm=name
super().__init__(species) # using super to declare the species
# attribute defined in Animal
sam=Dog('Canine','Sammi')
print(sam.sp)
print(sam.nm)

-------------------------------------------------------------------

class Car:
def __init__(self,model,make,year):
self.model=model
self.make=make
self.year=year
self.odometer=0
def spc(self):
full_det=f"{self.make} : {self.model} - {self.year}"
return full_det
def read(self):
print(f"This car odometer reading : {self.odometer} miles")
def update(self,milage):

14
self.odometer=milage
def incr(self,mile):
self.odometer+=mile
class Eleccar(Car):
def __init__(self,model,make,year):
'''Initialize attributes of the parent class.'''
super().__init__(model,make,year)
mycar=Eleccar('750S','BMW',2020)
car_det=Car("Camry","Toyota",2008)
print(car_det.spc())
car_det.odometer=2000
car_det.read()
car_det.update(5000)
car_det.read()
car_det.incr(300)
car_det.read()
print(mycar.spc())

Res :

Toyota : Camry - 2008


This car odometer reading : 2000 miles
This car odometer reading : 5000 miles
This car odometer reading : 5300 miles
BMW : 750S – 2020

 Defining Attributes and Methods for the Child Class


Once you have a child class that inherits from a parent class, you can add any new attributes
and methods necessary to differentiate the child class from the parent class.

class Eleccar(Car):
def __init__(self,model,make,year):
'''Initialize attributes of the parent class.'''
super().__init__(model,make,year)
self.sizebat=75
def battery(self):

 Overriding Methods from the Parent Class


To do this, you define a method in the child class with the same name as the method you want
to override in the parent class

# overriding methods defined in the superclass


class Animal():
def soundmake(self):
print('roar')
class Dog(Animal):

15
def soundmake(self):
print('bark')
sam , lion =Dog(),Animal() # declaring multiple variables on a single line
sam.soundmake() # overriding will call the makeSound method in Dog
lion.soundmake() # no overriding occurs as Animal does not inherit anything

16

You might also like