Python
Python
Note .............................................................................................................................................................. 1
Variables, Datatypes & Input Arithmetic Casting Data............................................................................. 17
List & Tuples Collection of Variables INDEPTH .......................................................................................... 19
Sets SETS Functions INDEPTH .................................................................................................................... 24
Dictionary List of Dictionaries INDEPTH .................................................................................................... 28
Conditional Statements IF ELIF ELSE NESTED ............................................................................................ 31
WHILE Loop Iterating Collections BREAK Keyword ................................................................................... 34
FOR Loop Iterating Collections BREAK Keyword ....................................................................................... 36
NESTED FOR Loop Iterating Multi-Dimensional Collections ..................................................................... 38
Functions Parameters or Arguments Return Values ................................................................................. 40
Arguments Arbitrary Arguments Keyword Arguments ............................................................................ 42
Lambda Shorthand Functions .................................................................................................................... 43
Classes & Objects Object Oriented Programming OOP ............................................................................ 44
Constructors Object Oriented Programming OOP .................................................................................... 45
Object Functions Object Oriented Programming ...................................................................................... 46
Inheritance Object Oriented Programming OOP ...................................................................................... 48
Collection of Objects Object Oriented Programming OOP ....................................................................... 51
Scoping & Importing Using Other Files or Directories .............................................................................. 54
Python Note
IDE & hello world
IDE An application that is used for the convenience of the user’s coding
experience on a certain programming language which provides tools to ease
the user’s labor.
Syntax:
print(“Hello World”)
IDENTIFIER The name of the variable which the user decides to choose
Syntax:
(identifier = value)
firstName = “DarKLter”
lastName = “Lesunter”
Syntax:
Variable = input(“Any Sentence”)
py 1
ARITHMETIC Used to perform mathematical operations inside our programming
OPERATORS language.
LISTS A Read and Write collection of variables that may be used to sort certain
data.
READING WHOLE You can read a list by printing the whole list.
LISTS Syntax:
print(list)
READING LISTS ITEMS You can read a list by printing one the items inside it by using an Index.
Syntax:
print(list[index])
+INDEX 0 1 2
-INDEX -3 -2 -1
Syntax:
courses = [“BSIT”,”BSCS”,”BLIS”]
READING LISTS You can read a list’s range of items by specifying a range of index.
RANGE Note: endIndex Item is excluded.
Syntax:
print(list[ startIndex : endIndex ])
print(list[ : endIndex ])
print(list[ startIndex : ])
ASSIGNING LIST You can assign a list item by using an index and an Assignment Operator “=”
ITEMS
Syntax:
list[index] = value
LIST LENGTH You can check the number of items in a list by using the len() function.
Syntax:
len(list)
py 2
LIST COUNT You can count how many times an item occurs in a list by using the count()
function.
Syntax:
[Link](value)
LIST ADD ITEMS BY append() adds an item at the END OF THE LIST.
APPEND()
Syntax:
[Link](value)
LIST DELETING ITEMS pop() deletes an item based on their index but if index is not specified it
BY POP() deletes the last item.
Syntax:
[Link]()
LIST DELETING ITEMS del deletes an item based on their index but if index is not specified it
BY DEL deletes the whole list.
Syntax:
del list[index]
Syntax:
[Link]()
COPYING A LIST copy() copies the whole list which can be assigned to a new list.
Example:
listOne = [“BSIT”,”BSCS”,”BLIS”]
listTwo = [Link]()
REVERSE LISTS ITEMS reverse() Reverses the order of the Lists items.
Syntax:
[Link]()
py 3
SORT LISTS ITEMS sort() Sort’s Lists Items by alphabet or value depending on the datatype.
Ascending Order
Syntax:
[Link]()
Descending Order
Syntax:
[Link](reverse=True)
Example:
courses = [“BSIT”,”BSCS”,”BLIS”[“DarKLter”,”Lesunter”]]
TUPLES A Read-Only Collection of variables that may be used to sort certain data.
Syntax:
identifier = (value,value1,value2)
Note:
1. Can be read.
2. Can be combined.
3. Can be deleted completely.
4. Can’t be assigned.
5. Can’t be deleted one by one.
SETS A Collection of Variables that is Partially Writable and its unordered and
unindexed.
Syntax:
identifier = {value,value1,value2}
READING WHOLE You can read a set by printing the whole set.
SETS
Syntax:
print(set)
READING SET ITEMS It is not possible to read certain item in a set unless you cast it into a List or
Tuple, hence Sets are unindexed and unordered.
ASSIGNING SET ITEMS It is not possible to change the value of a certain item in a set unless you cast
it into a List or Tuple, hence Sets are unindexed and unordered.
SET LENGTH You can check the number of items in a set by using the len() function.
Syntax:
len(set)
py 4
SET ADD ITEMS BY add() adds an item at the End Of The Set.
ADD()
Syntax:
[Link](value)
SET ADD ITEMS BY update() allows multiple items to be added at the same time in the set.
UPDATE()
Syntax:
[Link](list)
Syntax:
[Link](value)
SET DELETING ITEMS pop() deletes the first item in the Set.
BY POP()
Syntax:
[Link]()
Syntax:
[Link]()
COPYING A SET copy() copies the whole set which can be assigned to a new set.
Example:
setOne = {1,2,3,4,5}
setTwo = [Link]()
UNION SET union() returns a set containing all the value of the two sets.
Example:
setOne = {1,2,3,4,5}
setTwo = {6,7,8,9,10}
setThree = [Link](setTwo)
DIFFERENCE SET difference() returns a set containing the values that only exists on the left set
and not on right set.
Example:
setOne = {1,2,3,4,5}
setTwo = {3,4}
setThree = [Link](setTwo)
py 5
INTERSECTION SET intersection() returns a set containing the values that exists both on the two
sets.
Example:
setOne = {1,2,3,4,5}
setTwo = {3,4}
setThree = [Link](setTwo)
Example:
setOne = {1,2,3,4,5}
setTwo = {3,4,5,6,7}
setThree = setOne.symmetric_difference(setTwo)
DISJOINT SET isdisjoint() returns a Boolean whether two sets have an intersection or not.
Syntax:
[Link](setTwo)
SUBSET issubset() returns a Boolean whether the left set is contained in the right set.
Syntax:
[Link](setTwo)
SUPERSET issuperset() returns a Boolean whether the right set is contained in the left
set.
Syntax:
[Link](setTwo)
CASTING SETS You can cast Sets to Tuples or List and VICEVERSA in the same way you cast
other variables.
Syntax:
identifier = {
key1 : value1,
key2 : value2,
key3 : value3
}
READING WHOLE You can read a dictionary by printing the whole dictionary.
DICTIONARY
Syntax:
print(dictionary)
READING DICTONARY You can read a dictionary by specifying the Key Value.
ITEMS
Syntax:
print(dictionary[key])
py 6
ASSIGNING You can change a value of a certain in a dictionary by specifying the Key
DICTIONARY ITEMS Value and using the Assignment Operator “=”
Syntax:
dictionary[key] = value
DICTIONARY LENGTH You can check the number of items (key pairs) in a Dictionary by using the
len() function.
Syntax:
len(dictionary)
GETTING ALL KEYS IN keys() returns a list that contains all the keys inside your dictionary.
DICTIONARY
Syntax:
[Link]()
COPYING A copy() copies the whole which can be assigned to a new dictionary.
DICTIONARY
Example:
student = {“name” = “DarKLter” , ”gender” = ”Male”}
studentTwo = [Link]()
GETTING ALL VALUE value() return a list that contains all the value inside your dictionary.
IN DICTIONARY
Syntax:
[Link]()
CONDITIONAL A statement that makes the program smarter, it makes the program decides
STATEMENTS on what to do in certain CONDITIONS.
py 7
CONDITIONAL Are used to compare the value inside a Conditional Statements.
OPERATORS
== Equal
!= Not Equal
> Greater Than
< Less Than
>= GT or E
<= LT or E
Syntax:
if valueOne == valueTwo:
#Anything
Syntax:
if valueOne == valueTwo:
#Anything
else:
#Anything
Syntax:
if not valueOne == valueTwo:
#Anything
py 8
LOGICAL OPERATOR Used to include 2 or more Conditions in one line.
INDENTATION Indentation is used to Indicate what statements are included inside the
WHILE Loop.
WHILE LOOP A statement that will repeat a block of code as long as its condition is
fulfilled.
Syntax:
while valOne > valTwo:
#Anything
ELSE IN WHILE LOOP Else is added to the bottom of a while loop so that it can execute code when
the loop is done.
Syntax:
while valOne > valTwo:
#Anything
else:
#Anything
WHILE LOOP IN While loop can be used to access every item in a Collection (List & Tuples)
COLLECTION Since it is indexed and ordered
BREAK KEYWORDIN Break Keyword is used to stop the loop no matter what the condition is.
WHILE LOOP
CONDITION IN WHILE You can used any Conditional Statement inside a while loop.
LOOP
FOR Loop Iterating Collections BREAK Keyword
INDENTATION Indentation is used to Indicate what statements are included inside the FOR
Loop.
FOR LOOP IN For Loop can be used to access every item in a COLLECTION (List & Tuples) in
COLLECTION a very easy way.
Syntax:
for x in collection:
#Anything
py 9
ELSE IN FOR LOOP Else is added to the bottom of a while loop so that it can execute code when
the loop is done.
Syntax:
for x in collection:
#Anything
else:
#Anything
BREAK KEYWORD IN Break Keyword is used to stop the loop earlier than its supposed to finish.
FOR LOOP
CONDITION IN FOR You can used any Conditional Statement inside a for loop.
LOOP
RANGE() IN FOR LOOP Loops a set of code in specified number of times.
Syntax:
for x in range(y):
#Anything
NESTED FOR LOOP A For Loop inside a For Loop commonly used to iterate through a multi
dimentional collection.
FUNCTIONS Are used to organize and divide specific tasks in a program that will only run
when called.
Creating a Function
Syntax:
def function_name():
#Anything
Calling a Function
Syntax:
def function_name():
#Anything
function_name()
ARGUMENTS OR Are values passed inside a Function that will be used to perform tasks.
PARAMETERS
Syntax:
def function_name(parameters):
#Anything
function_name(values)
RETURN VALUES Is a value returned after a Function done executing it is used to get results
from a function that computes or does something that needs a result.
Syntax:
def function_name(parameter):
return value
function_name(parameter)
py 10
Arguments Arbitrary Arguments Keyword Arguments
ARBITRARY Arbitrary Arguments (*args) are used if you don’t exactly know how many
ARGUMENTS arguments is needed in your function.
Arbitrary Arguments that is passed in will be considered as a tuple allowing it
to be iterated using a loop.
Syntax:
def function_name(*parameter):
#Anything
function_name(v1,v2,v3…)
Syntax:
def function_name(*p1,p2):
#Anything
function_name(v1,v2,p2 = v3)
ARBITRARY Arbitrary Keyword Arguments (**kwargs) used when you are uncertain on
KEYWORD what parameter name you want to pass.
ARGUMENTS
Syntax:
def function_name(**paramenter):
#Anything
function_name(kword = v1, kword = v2)
LAMBDA Is a small Anonymous Function that can take any amount of Arguments but
can only have one Expression.
Syntax:
lambda p1,p2: expression
OBJECT ORIENTED It aims to implement real world objects/entities its attributes and behavior
PROGRAMMING into Programming so that we can represent it in our game, software or
applications.
Example:
Game Character
Real Life People (Students, Employees…)
Real Life Objects (Fruits, Table…)
Creating Objects
Syntax:
class className:
#Attributes
#Purpose / Function
Identifier = className()
py 11
CLASS Used in programming to make a blueprint for our object. It will represent
their attribute and purpose.
Example:
GAME CHARACTER: PRODUCT:
Purpose: Purpose:
Attributes: Attributes:
NAME ID
HP NAME
MP PRICE
ATK QUANTITY
LVL
Creating Classes
Syntax:
class className:
#Attributes
#Purpose / Function
Accessing Attibutes
Syntax:
class className:
#Attributes
#Purpose / Function
Identifier = className()
[Link] = value
print([Link])
CONSTRUCTORS Constructors are used to initialize an Object or simply put values on its
attributes when it is created.
_INIT_ FUNCTION init (initialize) function is called when an object is created it used as a
constructor.
Syntax:
class objectName:
def _init_(self):
#initialize code
py 12
SELF PARAMETER The self parameter in the parameter of _init_ is pertaining to itself the
object that is being created.
You can change the name of parameter as long as it the first parameter it
will always pertain to itself.
charOne = Character(“Alenere”,100,50,12,1)
OBJECT FUNCTIONS Any function declared inside an object class is considered an Object function.
Object Functions represents the object’s purpose.
Syntax:
class objectName:
def _init_(self):
#initialize code
def objFunc(self):
#Anything
SELF PARAMETER The First Parameter of all Object Functions is the self parameter it always
pertain to the object itself.
The self parameter name can be changed to anything as long as it is the first
parameter in the object function.
INHERITANCE Allows a child class to Inherit Methods and Attributes from a parent class.
Inheritance are used to create variations of an objects.
Parent Class
Syntax:
class parentClassName:
def _init_(self):
#initialize code
def objFunc(self):
#Anything
Child Class
Syntax:
class childClassName(parentClassName):
pass
PARENT CLASS Is the class where we inherit all the functions and Attributes they are also
called the Base Class or the Super Class.
CHILD CLASS Are variation of the Parent Class they have the same functions and attributes
but the Child Class has the ability to have their own functions and attributes
that the `Parent class doesn’t have.
py 13
OVERRIDING Parent Class
CONSTRUCTOR Syntax:
class parentClassName:
def _init_(self):
#initialize code
def objFunc(self):
#Anything
Child Class
Syntax:
class childClassName(parentClassName):
def _init_(self):
#initialize code
def objFunc(self):
#Anything
Child Class
Syntax:
class childClassName(parentClassName):
def _init_(self,attributes):
super()._init_(attributes)
#additional attributes
SUPER FUNCTION The super() can only be used by a child class, super() pertains to its parent
using that function we can access every function in our parent class inside
our child class.
Child Class
Syntax:
class childClassName(parentClassName):
def _init_(self):
#initialize code
def objFunc(self):
super().objFunc()
#Anything
py 14
Collection of Objects Object Oriented Programming OOP
listOfX = [x1,x2,x3]
print(listOfX[index].attributes)
listOfPeople = [p1,p2,p3]
for i in range(5):
name = input(“Name :”)
p = Person(name)
[Link](p)
py 15
Scoping & Importing Using Other Files or Directories
GLOBAL KEYWORD Enables You to change the global variable inside a function.
INPUT KEYWORD Let’s you use other files in your current file it is used to make cleaner
systems or to create your own library that can be reused on other’s project.
import Keywords are often used ion the topmost part of the code.
FROM KEYWORD Let’s you import certain variable, function, object etc. to your current file.
The From Keyword are used in combination with the Import Keyword.
py 16
Variables, Datatypes & Input Arithmetic
Casting Data
Example 1:
print("Hello World")
print("Hello Programmer")
Example 2:
firstName = "DarKLter"
lastName = "Lesunter"
number = 10
money = 25.50
isTall = True
Example 3:
Example 4:
firstName = "DarKLter"
number = 5
print(firstName + str(number))
Example 5:
money = "5.25"
number = 2
print(float(money) + number)
py 17
Example 5:
#Subtraction
print(5 - 2)
# Addition
print(5 + 2)
#Floor Division
print(5 // 2)
#Exponent
print(5 ** 2)
#Multiplication
print(5 * 2)
#Division
print(5 / 2)
#Modulus
print(5 % 2)
Example 6:
py 18
List & Tuples Collection of Variables
INDEPTH
#List
Example 1:
print(courses)
Example 2:
print(courses[0])
Example 3:
print(courses[-3])
Example 4:
print(courses[:3])
Example 5:
print(courses[3:])
Example 6:
print(courses[1:4])
Example 7:
print(courses)
py 19
Example 8:
print(len(courses))
Example 9:
print([Link]("Hatdog"))
Example 10:
print(courses)
Example 11:
print(courses)
Example 12:
print(courses)
Example 13:
print(courses)
Example 14:
print(courses)
py 20
Example 15:
del courses[3]
print(courses)
Example 16:
del courses
print(courses)
Example 17:
[Link]()
print(courses)
Example 18:
x = [Link]()
print(x)
Example 19:
[Link](3)
x = [Link]()
print(x)
Example 20:
print(courses + food)
Example 21:
print(coursesFood)
py 21
Example 22:
[Link](food)
print(courses)
Example 23:
[Link](food)
print(courses)
Example 24:
[Link]()
print(courses)
Example 25:
[Link]()
print(alphabet)
Example 26:
[Link](reverse = True)
print(alphabet)
Example 27:
print(courses[3][0][1])
py 22
#Cast List to Tuple, Tuple to List
Example 28:
print(courses)
Example 29:
courses = list(courses)
print(courses)
Example 30:
courses = tuple(courses)
print(courses)
py 23
Sets SETS Functions INDEPTH
EXAMPLE 1:
evenNumbers = {2,4,6,8,10}
print(evenNumbers)
EXAMPLE 2:
evenNumbers = {2,4,6,8,10}
print(len(evenNumbers))
EXAMPLE 3:
evenNumbers = {2,4,6,8,10}
[Link](12)
print(evenNumbers)
EXAMPLE 4:
evenNumbers = {2,4,6,8,10}
print(evenNumbers)
EXAMPLE 5:
evenNumbers = {2,4,6,8,10}
[Link]([12, 14, 16, 18, 20])
print(evenNumbers)
EXAMPLE 6:
evenNumbers = {2,4,6,8,10}
[Link](6)
print(evenNumbers)
EXAMPLE 7:
evenNumbers = {2,4,6,8,10}
[Link](6)
print(evenNumbers)
py 24
EXAMPLE 8:
evenNumbers = {2,4,6,8,10}
[Link](12)
print(evenNumbers)
EXAMPLE 9:
evenNumbers = {2,4,6,8,10}
[Link]()
[Link]()
print(evenNumbers)
EXAMPLE 10:
evenNumbers = {2,4,6,8,10}
[Link]()
print(evenNumbers)
EXAMPLE 11:
evenNumbers = {2,4,6,8,10}
setTwo = [Link]()
print(setTwo)
print(evenNumbers)
EXAMPLE 12:
evenNumbers = {2,4,6,8,10}
setTwo = [Link]()
[Link](12)
print(setTwo)
print(evenNumbers)
EXAMPLE 14:
evenNumbers = {2,4,6,8,10}
oddNumbers = {1,3,5,7,9}
numbers = [Link](oddNumbers)
print(numbers)
EXAMPLE 15:
numbers = {1,2,3}
numbersOne = {1,5,7}
numbersTwo = [Link](numbersOne)
print(numbersTwo)
py 25
EXAMPLE 16:
setOne = {1,2,3,4,5}
setTwo = {3,4}
setThree = [Link](setTwo)
print(setThree)
EXAMPLE 17:
setOne = {1,2,3,4,5}
setTwo = {3,4}
setThree = [Link](setOne)
print(setThree)
EXAMPLE 18:
setOne = {1,2,3,4,5}
setTwo = {3,4}
setThree = [Link](setTwo)
print(setThree)
EXAMPLE 19:
setOne = {1,2,3,4,5}
setTwo = {3,4,5,6,7}
setThree = setOne.symmetric_difference(setTwo)
print(setThree)
EXAMPLE 20:
evenNumbers = {2,4,6,8,10}
oddNumbers = {1,3,5,7,9}
print([Link](oddNumbers))
EXAMPLE 21:
evenNumbers = {2,4,6,8,10}
oddNumbers = {1,3,5,7,9,10}
print([Link](oddNumbers))
EXAMPLE 22:
numbers = {1,2,3,4,5,6,7,8,9,10}
evenNumbers = {2,4,6,8,10}
print([Link](numbers))
print([Link](evenNumbers))
EXAMPLE 23:
numbers = {1,2,3,4,5,6,7,8,9,10}
evenNumbers = {2,4,6,8,10}
print([Link](numbers))
print([Link](evenNumbers))
py 26
EXAMPLE 24:
numbers = {1,2,3,4,5,6,7,8,9,10}
evenNumbers = {2,4,6,8,10,11}
print([Link](numbers))
print([Link](evenNumbers))
EXAMPLE 25:
numbers = {1,2,3,4,5,6,7,8,9,10}
numbers = list(numbers)
numbers[0] = "Hatdog"
print(numbers)
EXAMPLE 26:
numbers = {1,2,3,4,5,6,7,8,9,10}
numbers = tuple(numbers)
print(numbers)
EXAMPLE 27:
numbers = [1,2,3,4,5,6,7,8,9,10]
numbers = set(numbers)
print(numbers)
py 27
Dictionary List of Dictionaries
INDEPTH
EXAMPLE 1:
studentOne = {
"name":"SDPT",
"course":"BSIT",
"age":18
}
studentTwo = {
"name":"John",
"course":"BSCS",
"age":19
}
print(studentOne)
print(studentTwo)
EXAMPLE 2:
studentOne = {
"name":"SDPT",
"course":"BSIT",
"age":18
}
studentTwo = {
"name":"John",
"course":"BSCS-",
"age":19
}
print(studentOne["name"])
print(studentTwo["name"])
EXAMPLE 3:
studentOne = {
"name":"SDPT",
"course":"BSIT",
"age":18
}
studentTwo = {
"name":"John",
"course":"BSCS-",
"age":19
}
print([Link]("name"))
print([Link]("name"))
EXAMPLE 4:
studentOne = {
"name":"SDPT",
"course":"BSIT",
"age":18
}
studentOne["name"] = "Bebang"
studentOne["age"] = 20
print([Link]("name"))
py 28
print([Link]("age"))
EXAMPLE 5:
studentOne = {
"name":"SDPT",
"course":"BSIT",
"age":18
}
studentOne["gender"] = "Male"
print(studentOne)
EXAMPLE 6:
studentOne = {
"name":"SDPT",
"course":"BSIT",
"age":18
}
[Link]("name")
print(studentOne)
EXAMPLE 7:
studentOne = {
"name":"SDPT",
"course":"BSIT",
"age":18
}
[Link]()
[Link]()
print(studentOne)
EXAMPLE 8:
studentOne = {
"name":"SDPT",
"course":"BSIT",
"age":18
}
[Link]()
print(studentOne)
EXAMPLE 9:
studentOne = {
"name":"SDPT",
"course":"BSIT",
"age":18
}
studentThree = [Link]()
studentOne["name"] = "Bebang"
print(studentOne)
print(studentThree)
py 29
EXAMPLE 10:
studentOne = {
"name":"SDPT",
"course":"BSIT",
"age":18
}
print([Link]())
EXAMPLE 11:
studentOne = {
"name":"SDPT",
"course":"BSIT",
"age":18
}
print([Link]())
EXAMPLE 12:
studentOne = {
"name":"SDPT",
"course":"BSIT",
"age":18
}
studentTwo = {
"name":"John",
"course":"BSCS",
"age":19
}
students = [studentOne,studentTwo]
print(students)
print(students[0].get("name"))
EXAMPLE 13:
studentOneAttributes = {
"height":172,
"weight":48,
"skin":"brown"
}
studentOne = {
"name":"SDPT",
"course":"BSIT",
"age":18,
"physical": studentOneAttributes
}
print([Link]("physical"))
print([Link]("physical").get("height"))
py 30
Conditional Statements IF ELIF
ELSE NESTED
EXAMPLE 1:
EXAMPLE 2:
EXAMPLE 3:
EXAMPLE 4:
EXAMPLE 5:
py 31
EXAMPLE 6:
EXAMPLE 7:
EXAMPLE 8:
EXAMPLE 9:
EXAMPLE 10:
hasMeterStick = False
hasRuler = True
if hasMeterStick or hasRuler:
print("Pasok KA")
else:
print("Pede Ka Nang Lumabas")
py 32
EXAMPLE 11:
hasMeterStick = False
hasRuler = True
if hasMeterStick and hasRuler:
print("Pasok KA")
else:
print("Pede Ka Nang Lumabas")
EXAMPLE 12:
hasMeterStick = False
hasRuler = True
hasBallpen = True
if hasMeterStick or hasRuler and hasBallpen:
print("Pasok KA")
else:
print("Pede Ka Nang Lumabas")
EXAMPLE 13:
bag =["wallet","gun","lipstick","computer","laptop"]
if "gun" in bag:
print("Huli Ka")
else:
print("Sige Pasok Ka")
EXAMPLE 14:
bag =["wallet","lipstick","computer"]
if "gun" in bag or "laptop" in bag and "computer" in bag:
print("Huli Ka")
else:
print("Sige Pasok Ka")
EXAMPLE 15:
py 33
WHILE Loop Iterating Collections
BREAK Keyword
EXAMPLE 1:
age = 12
while age < 18:
print("Still Young : " + str(age))
age = age + 1
EXAMPLE 2:
age = 12
while age < 18:
print("Still Young : " + str(age))
age = age + 1
EXAMPLE 3:
age = 12
while age < 18:
print("Still Young : " + str(age))
age = age + 1
else:
print("Legal Age : " + str(age))
EXAMPLE 4:
studentID = [2000123,2000124,2000125,2000126]
i = 0
while i <= 3:
print(i)
i = i + 1
EXAMPLE 5:
studentID = [2000123,2000124,2000125,2000126]
i = 0
while i <= 3:
print(studentID[i])
i = i + 1
EXAMPLE 6:
studentID = [2000123,2000124,2000125,2000126,2000127,2000128,2000129]
i = 0
py 34
EXAMPLE 7:
while True:
print("Hello World")
break
EXAMPLE 8:
while True:
answer = input("Answer : ")
if answer == "hindi":
print("CORRECT")
break
else:
print("NAGKAKAMALI KA KAPATID")
EXAMPLE 9:
numbers = [1,2,3,4,5,6,7,8,9,10]
i = 0
EXAMPLE 10:
lives = 3
correctAnswer = 150
py 35
FOR Loop Iterating Collections
BREAK Keyword
EXAMPLE 1:
fruits = ["Apple","Banana","Orange","Grapes","Avocado"]
for x in fruits:
print(x)
EXAMPLE 2:
fruits = ["Apple","Banana","Orange","Grapes","Avocado"]
for x in fruits:
print(x)
else:
print("No More Fruits")
EXAMPLE 3:
fruits = ["Apple","Banana","Orange","Grapes","Avocado"]
for x in fruits:
print(x)
if x == "Orange":
break
EXAMPLE 4:
fruits = ["Apple","Banana","Orange","Grapes","Avocado"]
for x in fruits:
print(x)
if x == "Apple":
print("An Apple is on the tree")
elif x == "Orange":
print("Orange Pero Green")
EXAMPLE 5:
numbers = [1,2,3,4,5,6,7,8,9,10]
EXAMPLE 6:
for x in range(5):
print("Hello World")
py 36
EXAMPLE 7:
userName = ["Lesunter","DarKLter","KLter",]
passWord = ["123abc","124abc","125abc"]
for x in range(len(userName)):
print(userName[x] + " " + passWord[x])
EXAMPLE 8:
username = ["Lesunter","DarKLter","KLter"]
password = ["123abc","124abc","125abc"]
for x in range(len(username)):
if currUsername == username[x] and currPassword == password[x]:
print("Welcome Back " + username[x])
break
else:
print("Account Not Found!")
py 37
NESTED FOR Loop Iterating
Multi Dimensional Collections
EXAMPLE 1:
for x in range(3):
print("tae")
for y in range(3):
print("Hello World")
EXAMPLE 2:
print("tae",end="")
print("*")
EXAMPLE 3:
for x in range(3):
for y in range(5):
print("tae",end="")
print()
EXAMPLE 4:
for x in range(3):
print()
for y in range(5):
print("tae",end="")
print(" na green")
EXAMPLE 5:
courseStuddents = [
["BSIT","David"],
["BSIT","Alenere"],
["BSCS","Patrick"],
["BSCS","Jaymar"],
["BSCS","Emman"]
]
print(courseStuddents[3][1])
EXAMPLE 6:
courseStuddents = [
["BSIT","David"],
["BSIT","Alenere"],
["BSCS","Patrick"],
["BSCS","Jaymar"],
["BSCS","Emman"]
]
for x in courseStuddents:
print(x)
py 38
EXAMPLE 7:
courseStuddents = [
["BSIT","David"],
["BSIT","Alenere"],
["BSCS","Patrick"],
["BSCS","Jaymar"],
["BSCS","Emman"]
]
for x in courseStuddents:
print(x[1])
EXAMPLE 8:
courseStuddents = [
["BSIT","David"],
["BSIT","Alenere"],
["BSCS","Patrick"],
["BSCS","Jaymar"],
["BSCS","Emman"]
]
for listStudent in courseStuddents:
for i in listStudent:
print(i)
print()
EXAMPLE 9:
students = [
["BSIT",["David","Alenere"]],
["BSCS",["Patrick","Jaymar","Emman"]],
["BLIS",["Kristian","Bob","John"]]
]
for i in students:
print(i[0])
for x in i[1]:
print(" -" + x)
print()
py 39
Functions Parameters or Arguments
Return Values
EXAMPLE 1:
def sayHello():
print("Hello")
print("World")
sayHello()
EXAMPLE 2:
def sayHello(firstName):
print("Hello, " + firstName)
EXAMPLE 3:
def sayHello(firstName,lastName):
print("Hello, " + firstName +" "+ lastName)
sayHello("Karl Lester","Paular")
EXAMPLE 4:
def add(numOne,numTwo):
return numOne + numTwo
def subtract(numOne,numTwo):
return numOne - numTwo
sum = add(5,3)
print(sum)
difference = subtract(5,3)
print(difference)
EXAMPLE 5:
def isLegalAge(age):
if age >= 18:
return True
else:
return False
print(isLegalAge(18))
py 40
EXAMPLE 6:
def square(num):
return num * num
EXAMPLE 7:
def square(num):
numbers = num * num
return numbers
py 41
Arguments Arbitrary Arguments
Keyword Arguments
EXAMPLE 1:
def sayHello(*names):
print(names)
sayHello("SDPT","Alenere","David","Bob","Jet","John","Doe")
EXAMPLE 2:
def sayHello(*names):
for name in names:
print("Hello, " + name)
sayHello("SDPT","Alenere","David","Bob","Jet","John","Doe")
EXAMPLE 3:
def sayHello(firstName,lastName):
print(firstName + " " + lastName)
sayHello(lastName="Solution",firstName="SDPT")
EXAMPLE 4:
def printFAMILY(*firstName,lastName):
for name in firstName:
print(name + " " + lastName)
printFAMILY("SDPT","Alenere","Bob","John","David",lastName="HATDOG")
EXAMPLE 5:
def printStudent(**student):
print("Name : " + student["name"])
print("Course : " + student["course"])
print("Age : " + str(student["age"]))
print("Average : " + str(student["average"]))
print("CourseCode : " + str(student["coursecode"]))
printStudent(name="SDPT",age=18,course="BSIT",average=90,coursecode=101)
EXAMPLE 6:
def summationOf(*numbers):
sum = 0
for number in numbers:
sum += number
return sum
py 42
Lambda Shorthand Functions
EXAMPLE 1:
print(add(2,3,5))
print(add(2,5,5))
print(add(5,3,5))
print(add(3,3,5))
EXAMPLE 2:
tripler = lambda x: x * 3
EXAMPLE 3:
tripler = lambda x: x * 3
py 43
Classes & Objects Object Oriented
Programming OOP
EXAMPLE 1:
class Character:
name = "Name"
hp = 100
mp = 50
atk = 12
lvl = 1
charOne = Character()
charTwo = Character()
[Link] = "Alenere"
[Link] = 200
[Link] = 100
[Link] = 50
[Link] = 5
print([Link])
print([Link])
EXAMPLE 2:
class Product:
ID = 1000
name = "name"
qty = 0
productOne = Product()
[Link] = 10001
[Link] = "Milk"
[Link] = 5
print([Link])
print([Link])
print([Link])
py 44
Constructors Object Oriented
Programming OOP
EXAMPLE 1:
class Character:
def __init__(self):
print("Character Created")
charOne = Character()
charTwo = Character()
charThree = Character()
EXAMPLE 2:
class Character:
def __init__(self,name,hp,mp,atk,lvl):
[Link] = name
[Link] = hp
[Link] = mp
[Link] = atk
[Link] = lvl
print("Created " + [Link])
charOne = Character("David",200,100,15,2)
charTwo = Character("Alenere",100,400,12,3)
py 45
Object Functions Object Oriented
Programming
EXAMPLE 1:
class Animal:
def __init__(self,type,voice):
[Link] = type
[Link] = voice
aOne = Animal("Dog","Arf")
print([Link])
EXAMPLE 2:
class Animal:
def __init__(self,type,voice):
[Link] = type
[Link] = voice
def speak(self):
print([Link])
aOne = Animal("Dog","Arf")
[Link]()
EXAMPLE 3:
class Animal:
def __init__(self,type,voice):
[Link] = type
[Link] = voice
def speak(self):
print([Link])
def introduceSelf(self):
print("I am a " + [Link])
aTwo = Animal("Cat","Meow")
[Link]()
[Link]()
py 46
EXAMPLE 4:
class User:
def __init__(self,firstName,lastName,likeCount,friendName):
[Link] = firstName
[Link] = lastName
[Link] = likeCount
[Link] = friendName
print("User Created Name : " + [Link])
def intoduceSelf(self):
print("Hi I'am " + [Link] + " " + [Link])
def fullProfile(self):
print("Full Name : " + [Link] + " " + [Link])
print("Like : "+ str([Link]))
print("Friends")
for friend in [Link]:
print(" -" + friend)
py 47
Inheritance Object Oriented
Programming OOP
EXAMPLE 1:
class Person:
def __init__(self,firstName,lastName):
[Link] = firstName
[Link] = lastName
def introduceSelf(self):
print("Hi I'am " + [Link] + " " + [Link])
class Student(Person):
pass
p1 = Person("David","Sdpt")
[Link]()
s1 = Student("Alenere","Sdpt")
[Link]()
EXAMPLE 2:
class Person:
def __init__(self,firstName,lastName):
[Link] = firstName
[Link] = lastName
def introduceSelf(self):
print("Hi I'am " + [Link] + " " + [Link])
class Student(Person):
def __init__(self,firstName,lastName,sectionYear):
super().__init__(firstName,lastName)
[Link] = sectionYear
p1 = Person("David","Sdpt")
s1 = Student("Alenere","Sdpt","1-E")
EXAMPLE 3:
class Person:
def __init__(self,firstName,lastName):
[Link] = firstName
[Link] = lastName
def introduceSelf(self):
print("Hi I'am " + [Link] + " " + [Link])
class Student(Person):
def __init__(self,firstName,lastName,sectionYear):
super().__init__(firstName,lastName)
[Link] = sectionYear
def introduceSelf(self):
print("Hi I'am " + [Link] + " " + [Link] + " FROM " +
[Link])
p1 = Person("David","Sdpt")
s1 = Student("Alenere","Sdpt","1-E")
[Link]()
[Link]()
py 48
EXAMPLE 4:
class Person:
def __init__(self,firstName,lastName):
[Link] = firstName
[Link] = lastName
def introduceSelf(self):
print("Hi I'am " + [Link] + " " + [Link])
class Student(Person):
def __init__(self,firstName,lastName,sectionYear):
super().__init__(firstName,lastName)
[Link] = sectionYear
def introduceSelf(self):
print("From " + [Link])
super().introduceSelf()
p1 = Person("David","Sdpt")
s1 = Student("Alenere","Sdpt","1-E")
[Link]()
[Link]()
EXAMPLE 5:
class Student(Person):
def __init__(self,firstName,lastName,sectionYear):
super().__init__(firstName,lastName)
[Link] = sectionYear
def introduceSelf(self):
super(Student, self).introduceSelf()
print("From " + [Link])
class Employee(Person):
def __init__(self,firstName,lastName,salary):
super().__init__(firstName,lastName)
[Link] = salary
def introduceSelf(self):
super().introduceSelf()
print("My salary is " + str([Link]))
p1 = Person("David","Sdpt")
s1 = Student("Alenere","Sdpt","1-E")
e1 = Employee("Patrick","Macaraig",5000)
[Link]()
[Link]()
[Link]()
py 49
EXAMPLE 6:
class Person:
def __init__(self,firstName,lastName):
[Link] = firstName
[Link] = lastName
def introduceSelf(self):
print("Hi I'am " + [Link] + " " + [Link])
def introduceLastName(self):
print("Hi I'am " + [Link])
class Student(Person):
def __init__(self,firstName,lastName,sectionYear):
super().__init__(firstName,lastName)
[Link] = sectionYear
def introduceSelf(self):
super(Student, self).introduceSelf()
print("From " + [Link])
def saySection(self):
print([Link])
class Employee(Person):
def __init__(self,firstName,lastName,salary):
super().__init__(firstName,lastName)
[Link] = salary
def introduceSelf(self):
super().introduceSelf()
print("My salary is " + str([Link]))
def saySalary(self):
print("Salary : " + str([Link]))
p1 = Person("David","Sdpt")
[Link]()
[Link]()
s1 = Student("Alenere","Sdpt","1-E")
[Link]()
[Link]()
[Link]()
e1 = Employee("Patrick","Macaraig",5000)
[Link]()
[Link]()
[Link]()
py 50
Collection of Objects Object Oriented
Programming OOP
EXAMPLE 1:
class Person:
def __init__(self,name):
[Link] = name
print([Link] + " Create")
EXAMPLE 2:
class Person:
def __init__(self,name):
[Link] = name
print([Link] + " Create")
p1 = Person("David")
p2 = Person("Alenere")
p3 = Person("Jaymar")
listOfPeople = [p1,p2,p3]
print(listOfPeople[1].name)
EXAMPLE 3:
class Person:
def __init__(self,name):
[Link] = name
p1 = Person("David")
p2 = Person("Alenere")
p3 = Person("Jaymar")
listOfPeople = [p1,p2,p3]
print(listOfPeople[1].name)
EXAMPLE 4:
class Person:
def __init__(self,name):
[Link] = name
def introduce(self):
print("I'am " + [Link])
p1 = Person("David")
p2 = Person("Alenere")
p3 = Person("Jaymar")
listOfPeople = [p1,p2,p3]
print(listOfPeople[1].introduce())
py 51
EXAMPLE 5:
class Person:
def __init__(self,name):
[Link] = name
def introduce(self):
print("I'am " + [Link])
p1 = Person("David")
p2 = Person("Alenere")
p3 = Person("Jaymar")
p4 = Person("Joshwa")
listOfPeople = [p1,p2,p3,p4]
EXAMPLE 6:
class Person:
def __init__(self,name):
[Link] = name
def introduce(self):
print("I'am " + [Link])
listOfPeople = []
for i in range(3):
name = input("Enter Name : ")
p = Person(name)
[Link](p)
py 52
EXAMPLE 7:
class Student:
def __init__(self,name,course,year,section):
[Link] = name
[Link] = course
[Link] = year
[Link] = section
def introduce(self):
print(" Name : " + [Link])
print(" Course : " + [Link])
print(" Year : " + [Link])
print(" Secion : " + [Link])
listOfStudent = []
while True:
name = input("Name : ")
course = input("Course : ")
year = input("Year : ")
section = input("Section : ")
s = Student(name,course,year,section)
[Link](s)
print("\n")
i = 1
print()
print("***List Of Student***")
py 53
Scoping & Importing Using Other
Files or Directories
EXAMPLE 1:
#LOCAL VARIABLES
def sayHello():
x = "Say Hello"
print(x)
print(y)
#PARAMATER VARIABLES
def say(word):
print(word)
#GLOBAL VARIABLES
y = "World"
sayHello()
say("What")
EXAMPLE 2:
#GLOBAL VARIABLES
y = "World"
#GLOBAL KEYWORD
def say():
y = "Hello"
print(y)
say()
print(y)
EXAMPLE 3:
#GLOBAL VARIABLES
y = "World"
#GLOBAL VARIABLES
def say():
global y
y = "Hello"
print(y)
say()
print(y)
py 54
EXAMPLE 4:
[Link]
def add(x,y):
return x + y
def subtract(x,y):
return x - y
def multiply(x,y):
return x * y
def divide(x,y):
return x / y
[Link]
class Student:
def __init__(self,name,course):
[Link] = name
[Link] = course
def introduce(self):
print("I'am " + [Link] + " and I'am " + [Link] + " Student")
[Link]
pi = 3.141
[Link]
import Arithmetic
import Constants
import Objects
s1 = [Link]("David","BSIT")
[Link]()
print([Link])
print([Link](5,2))
py 55
EXAMPLE 1 : [Link]
import Arithmetic as a
import Constants as c
import Objects as o
s1 = [Link]("David","BSIT")
[Link]()
print([Link])
print([Link](5,2))
EXAMPLE 2 : [Link]
s1 = Student("David","BSIT")
[Link]()
print(a(5,2))
print(pi)
s1 = Student("David","BSIT")
[Link]()
print(a(5,2))
print(pi)
py 56