Professional Documents
Culture Documents
“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
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
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)
4
print(alien) ---} {'color': 'green', 'points': 5}
{'color': 'green', 'points': 5, 'y_position': 25, 'x_position': 0}
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}")
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
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 }")
Functions parameter
def greet_user(username):
print(f"Hello, {username.title()}!")
greet_user('jesse') - calling
argument
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.
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')
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
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
# 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.
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()
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()
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.
sam=Dog()
sam.makesound() # accessible through inheritance
lion=Animal()
# lion.species not accessible, inheritance does not work backwards
-------------------------------------------------------------------
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 :
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):
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