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

python basics

The document provides an overview of basic and advanced data types in programming, including variables, lists, tuples, and sets, along with their syntax and examples. It covers operations such as printing, inputting, arithmetic operations, and manipulating data structures like adding, removing, and counting items. The document serves as a guide for understanding fundamental programming concepts and operations.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

python basics

The document provides an overview of basic and advanced data types in programming, including variables, lists, tuples, and sets, along with their syntax and examples. It covers operations such as printing, inputting, arithmetic operations, and manipulating data structures like adding, removing, and counting items. The document serves as a guide for understanding fundamental programming concepts and operations.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Name: Elmar Reymond A.

Delac Cruz Page # 1


Contact No.: 0966-560-8740 Created by: Elmar

1. printing out 5. Casting variables


Used to display something in the console. A Technique used to convert a datatype to another
datatype.
SYNTAX:
print(“Hello World!”) SYNTAX:
Converting Numbers to String
2. Variables str(number)
Variables are used to store up data for later use. Converting String to Numbers
int (string)
BASIC DATA TYPES: float (string)
Data Type Use for Example
string Sentences, Identifier = “Hello World” Ex code.
Phrases, Character
int Positive & Identifier = 5 firstName = “Elmarr”
negative numbers number = 15
float Decimal Numbers Identifier = 25.3237
bool True or False Identifier = true print (firstname + str(number))

ADVANCED DATA TYPES: Ex code.


 List  Frozenset st
 Tuple  Bytes
Num1 = int ( input ( “Enter 1 number: ” ))
nd
Num2 = int ( input ( “Enter 2 number: ” ))
 Dict  Bytearray
 Set  Memoryview result = Num1 + Num2

3. IDENTIFIERS print ( str ( Num1 ) “ + ” str (Num2) “ = ” str (result ) )


The name of the variable which the user decides to
choose.
6. Arithmetic Operators
Used to perform mathematical operation inside our
SYNTAX:
programming language.
(Identifier = value)
firstName = “Elmarr”
Operator Syntax Result
lastName = “Dela_Cruz”
Subtraction x–y Difference
PRINTING VARIABLE Addition x+y Sum
Multiplication x*y Product
Ex code. Division x/y Quotient
Modulus x%y Remainder
firstName = “Elmarr” Floor Division x // y Quotient (Rounded Off)
lastName = “Dela_Cruz” Exponent x ** y Power

print (fisrstName + “ ” + lastName)


Ex code.
4. INPUTING
print (15 – 1) #Subtraction
Used to make the user input something in the
console. print (15 + 1) #Addition
print (15 * 1) #Multiplication
SYNTAX:
Variable = input() print (15 / 1) #Division
print (15 % 1) #Modulus
Ex code. Ex code.
print (15 // 1) #Floor Division
Age = input() name = input(“Enter your name: ”)
print(Age) print( “Hi” + name) print (15 ** 1) #Exponent
Name: Elmar Reymond A. Delac Cruz Page # 2
Contact No.: 0966-560-8740 Created by: Elmar

7. Comments ( # ) Reading List RANGE


Provides a context or clarify intent, this adds a extra You can read a list’s range of items by specifying a
descriptions to the code. range of index.

Ex code. SYNTAX:
firstName = “Elmarr” #set variable value print ( list [startIndex : endIndex] )
print ( list [ : endIndex] )
print (firstname) #print the value print ( list [ startIndex : ] )

Note: endindex item is excluded.


8. Lists
Ex code.
A Read and Write Collection of variables that may
be used to sort certain data names = [“elmarr”, “reymond”, “arroyo”, “dela_cruz”, “momon”]

SYNTAX: print ( names [0 : 4] ) #always +1 to end index


Identifier = [value0, value1, value2]
Ex code.
Ex code.
names = [“elmarr”, “reymond”, “arroyo”, “dela_cruz”, “momon”]
names = [“elmarr”, “reymond”, dela_cruz”]
print ( names [ : 4] ) #always +1 to end index

Reading WHOLE Lists Ex code.


You can read a list by printing the whole list.
names = [“elmarr”, “reymond”, “arroyo”, “dela_cruz”, “momon”]
SYNTAX:
print ( list ) print ( names [1 : ] )

Ex code.
Assigning List ITEMS
names = [“elmarr”, “reymond”, dela_cruz”] You can assign a list item by using an INDEX and an
Assignment Operator “=”.
print ( names )
SYNTAX:
Reading Lists ITEMS list [index] = value
You can read a list by printing one of the items
Ex code.
inside it by using an INDEX. names = [“elmarr”, “reymond”, “arroyo”, “dela_cruz”, “momon”]

SYNTAX: names [0] = “mon”


print ( list [ index ] ) print ( names )

INDEX List LENGTH


The number of where an item is on a collection. You can check the number of items in a list by using
the len() function.
+ INDEX: 0 1 2
- INDEX: -3 -2 -1 SYNTAX:
names = [“elmarr”, “reymond”, dela_cruz”] len (list)
Ex code. Ex code.
names = [“elmarr”, “reymond”, “arroyo”, “dela_cruz”, “momon”]
names = [“elmarr”, “reymond”, dela_cruz”]
print ( len (names) )
print ( names [2] )

Ex code.

names = [“elmarr”, “reymond”, dela_cruz”]

print ( names [-1] )


Name: Elmar Reymond A. Delac Cruz Page # 3
Contact No.: 0966-560-8740 Created by: Elmar

List COUNT List DELETING ITEMS by POP()


You can count how many times an items an item pop() deletes an item based on their index but if
occurs in a list by using the count() function. index is not specified it deteles the last item.

SYNTAX: SYNTAX:
list.count(value) list.pop()
Ex code. list.pop(index)
names = [“elmarr”, “reymond”, “arroyo”, “dela_cruz”, “elmarr”] Ex code.
names = [“elmarr”, “reymond”, “arroyo”, “dela_cruz”]
print ( names.count(“elmarr”) )
names.pop ()
List ADD ITEMS by APPEND() print ( names)
append() adds an item at the END OF THE LIST.
Ex code.
SYNTAX: names = [“elmarr”, “reymond”, “arroyo”, “dela_cruz”]
list.append(value)
names.pop (3)
Ex code. print ( names )
names = [“elmarr”, “reymond”, “arroyo”]

names.append (“dela_cruz”) List DELETING ITEMS by DEL


print ( names) del deletes an item based on their index but if
index is not specified it deletes the whole list.
List ADD ITEMS by INSERT()
insert() adds an item at the SPECFIED INDEX. SYNTAX:
del list[index]
SYNTAX: del list
list.insert(index,value) Ex code.
Ex code. names = [“elmarr”, “reymond”, “arroyo”, “dela_cruz”]
names = [“elmarr”, “reymond”, “dela_cruz”]
del names (2)
names.insert (2, “arroyo”) print ( names )
print ( names)
Ex code.
List DELETING ITEMS by REMOVE() names = [“elmarr”, “reymond”, “arroyo”, “dela_cruz”]
remove() deletes an item based on their value.
del names
SYNTAX: print ( names )
list.remove(value)
Clearing a List
Ex code.
names = [“elmarr”, “reymond”, “arroyo”, “dela_cruz”]
clear() deletes all the value in list.

names.remove ( “arroyo”) SYNTAX:


print ( names) list.clear()
Ex code.
names = [“elmarr”, “reymond”, “arroyo”, “dela_cruz”]

names.clear()
print ( names )
Name: Elmar Reymond A. Delac Cruz Page # 4
Contact No.: 0966-560-8740 Created by: Elmar

Copying a List REVERSE Lists Items


copy() copies the whole list which canassigned to a reverse() Reverses the order of the List’s Items.
new list.
SYNTAX:
SYNTAX: list.reverse()
listOne = [value0, value1, value2] Ex code.
listTwo = listOne.copy() numbers = [1, 2, 3, 4, 5]
Ex code.
names = [“elmarr”, “reymond”, “arroyo”, “dela_cruz”] numbers.reverse()
print ( numbers )
x = names.copy()
print ( x ) SORT Lists Items
sort() Sort’s List’s Items by Alphabet or Value
COMBINING Lists by ADDING depending on the datatype.
You can use ‘+’ operators to combine lists.
SYNTAX:
SYNTAX: list.sort() #Ascending Order
listOne = [value0, value1, value2] list.sort(reverse=True) #Descending Order
listTwo = [value3, value4, value5] Ex code. Ex code.
listThree = listOne + listTwo #Ascending Order #Descending Order
numbers = [4, 2, 5, 3, 1] numbers = [4, 2, 5, 3, 1]
Ex code.
names = [“elmarr”, “reymond”, “dela_cruz”]
numbers.sort() numbers.sort(reverse = True)
places = [“Makati”, “Marikina”, “Manila”]
namesPlaces = names + places print ( numbers ) print ( numbers )

print ( namesPlaces ) NESTED Lists


A List inside a List also known as sublist.
COMBINING Lists by EXTEND()
extend() combines lists by appending the specified SYNTAX:
list to the end of the first list. list = [value0, value1, value2[value3, value4]]
Ex code. Ex code.
SYNTAX: #index 0 1 2 3
# 0 1 2 3
listOne = [value0, value1, value2] numbers = [1, 2, 3, [4, 5]] #index 0 1
listTwo = [value3, value4, value5] numbers = [1, 2, 3, [4, 5]]
listOne.extend(listTwo) print ( numbers [2] )
print ( numbers [3][1] )
listOne = [value0, value1, value2]
listTwo = [value3, value4, value5] Ex code.
#index 0 1 2 3
listOne.append(listTwo) #index 0 1
#index 0 1
Ex code. numbers = [1, 2, 3, [[4, 5], 6]]
names = [“elmarr”, “reymond”, “dela_cruz”]
places = [“Makati”, “Marikina”, “Manila”] print ( numbers [3][0][1] )
names.extend(places)

print ( names )

Ex code.
names = [“elmarr”, “reymond”, “dela_cruz”]
places = [“Makati”, “Marikina”, “Manila”]
names.append(places)

print ( names )
Name: Elmar Reymond A. Delac Cruz Page # 5
Contact No.: 0966-560-8740 Created by: Elmar

8. Tuples Set ADD ITEMS by ADD()


A Read-Only Collection of variables that may be add() adds an item at the END OF THE SET.
used to sort certain data.
SYNTAX:
List Tuples set.add(value)
Can read Can read Ex code.
Can combined Can combined evenNumbers = {2, 4, 6, 8, 10}
Can deleted completely Can deleted completely evenNumbers.add (12)
Can assign Can’t assign
Can deleted one by one Can’t deleted one by one print ( evenNumbers )
Use “[]” Use “()”
Set ADD ITEMS by UPDATE()
SYNTAX: update() allows multiple items to be added at the
Identifier = (value0, value1, value2) same time in the set.

9. Sets SYNTAX:
A Collection of variables that is Partially Writable set.update (list)
and it’s unordered and unindexed. Ex code. Ex code.
evenNumbers = {2, 4, 6, 8, 10} evenNumbers = {2, 4, 6, 8, 10}
SYNTAX: evenNumbers.update ([12, 14, 16]) extend = [12, 14, 16]
evenNumbers.update (extend)
Identifier = {value0, value1, value2}
print ( evenNumbers )
print ( evenNumbers )
Reading WHOLE Sets
You can read a set by printing the whole set.
Set DELETING ITEMS by REMOVE()
SYNTAX: remove() deletes an item based on their value.
print (set)
SYNTAX:
Ex code. set.remove(value)
evenNumbers = {2, 4, 6, 8, 10}
PS: If the value doesn’t exist in the set it will be
print ( evenNumbers )
counted as an error.
Reading Set ITEMS Ex code.
It is not possible to read certain item in a set unless evenNumbers = {2, 4, 6, 8, 10}
you cast into a List or Tuple. Hence Sets are evenNumbers.remove (6)
unindexed and unordered. print ( evenNumbers )

Assigning Set ITEMS


it is not possible to change the value of a certain Set DELETING ITEMS by DISCARD()
item in a set unless you cast it into a List or Tuple. discard() deletes an item based on their value.

Set LENGTH Syntax:


You can check the number of items in a set by using set.discard(value)
the len() function.
PS: If the value doesn’t exist in the set it will NOT be
SYNTAX: counted as an ERROR.
len( set ) Ex code.
Ex code. evenNumbers = {2, 4, 6, 8, 10}
evenNumbers = {2, 4, 6, 8, 10} evenNumbers.discard (20)

print ( len (evenNumbers) ) print ( evenNumbers )


Name: Elmar Reymond A. Delac Cruz Page # 6
Contact No.: 0966-560-8740 Created by: Elmar

Set DELETING ITEMS by POP() DIFFERENCE Set


pop() deletes the first item in the Set. difference() returns a set containing the values that
only exists on the left set and not on the right set.
SYNTAX:
set.pop() SYNTAX:
Ex code. setOne = {1, 2, 3 }
evenNumbers = {2, 4, 6, 8, 10} setTwo = {2, 3 }
evenNumbers.pop() setThree = setOne.difference(setTwo)
print ( evenNumbers ) Ex code.
Num1 = {1, 2, 3, 4, 5}
Num2 = {3, 4}
Clearing a SET numbers = Num1.difference(Num2)
clear() deletes all the value in a set. print (numbers)

SYNTAX:
set.clear() INTERSECTION Set
Ex code. intersection() returns a set containing the values
evenNumbers = {2, 4, 6, 8, 10} that exists both on the two sets.
evenNumbers.clear()
SYNTAX:
print ( evenNumbers )
setOne = {value0, value1, value2}
setTwo = {value1, value2}
Copying a Set setThree = setOne.intersection(setTwo)
copy() copies the whole set which can be assigned to
Ex code.
a new set. Num1 = {1, 2, 3}
Num2 = {2, 3}
SYNTAX: numbers = Num2.intersection(Num1)
setOne = {value0, value1, value2}
print (numbers)
setTwo = setOne.copy()
Ex code.
setOne = {2, 4, 6, 8, 10}
SYMETRIC DIFFRENCE Set
setTwo = setOne.copy() symmetric_difference() returns a set containing all
values that exists EXCLUSIVELY on each set.
print (setOne)
SYNTAX:
UNION Set setOne = {1, 2, 3, 4, 5}
union() returns a set containing all the values of the setTwo = {3, 4, 5, 6, 7}
two sets. setThree = setOne.intersection(setTwo)
Ex code.
SYNTAX: Num1 = {1, 2, 3, 4}
setOne = {value0, value1, value2} Num2 = {2, 3, 4, 5}
numbers = Num2.symmetric_difference (Num1)
setTwo = {value3, value4, value5}
setThree = setOne.union(setTwo) print (numbers)
Ex code.
evenNum = {2, 4, 6, 8, 10}
oddNum = {1, 3, 5, 7, 9} DISJOINT Set
numbers = evenNum.union(oddNum) isdisjoint() returns a Boolean whether two sets have
an intersection or not.
print (setOne)

Ex code. SYNTAX:
Num1 = {1, 2, 3} setOne.isdisjoint(setTwo)
Num2 = {1, 4, 5}
Ex code. Ex code.
numbers = Num1.union(Num2)
evenNum = {2, 4, 6, 8, 10} evenNum = {2, 4, 6, 8, 10}
oddNum = {1, 3, 5, 7, 9} oddNum = {1, 3, 5, 7, 9, 10}
print (numbers)
print (evenNum.isdisjoint(oddNum)) print (evenNum.isdisjoint(oddNum))
Name: Elmar Reymond A. Delac Cruz Page # 7
Contact No.: 0966-560-8740 Created by: Elmar

SUBSET Reading Dictionary ITEMS


issubset() returns a Boolean whether the left set is You can read a dictionary by specifying the Key
contained in the right set. Value.

SYNTAX: SYNTAX:
setOne.issubset(setTwo) print(dictionary[key])
Ex code. Ex code. Ex code.
numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} studentOne = {
evenNum = {2, 4, 6, 8, 10} evenNum = {2, 4, 6, 8, 10, 11} “name” : “elmarr”,
“course” : “BSIT”,
print (evenNum.issubset(numbers)) print (evenNum.issubset(numbers)) “age” : 15
}
studentTwo = {
SUPERSET “name” : “reymondr”,
issuperset() returns a boolean whether the right set “course” : “BSCs”,
“age” : 20
is contained in the left set.
}

SYNTAX: print (studenOne [“name”])


setOne.issuperset(setTwo) print (studentTwo [“age”])
Ex code. Ex code.
numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} Reading Dictionary ITEMS GET
evenNum = {2, 4, 6, 8, 10} evenNum = {2, 4, 6, 8, 10, 11}
You can also use GET to read a dictionary by
print (numbers.issuperset(evenNum)) print (numbers.issuperset(evenNum)) specifying the Key Value.

SYNTAX:
CASTING SETS
You can cast Sets to Tuples or List and VICEVERSA in print(dictionary.get(key))
the same way you cast other variables. Ex code.
studentOne = {
Ex code. Ex code.
numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] “name” : “elmarr”,
numbers = list(numbers) numbers = set(numbers) “course” : “BSIT”,
“age” : 15
print (numbers) print (numbers) }
studentTwo = {
Ex code. “name” : “reymondr”,
numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} “course” : “BSCs”,
numbers = tuple(numbers) “age” : 20
}
print (numbers)

print (studenOne .get(“name”))


9. Dictionary print (studentTwo.get(“age”))
A Collection of Key Pairs that is Unordered
Assigning Dictionary ITEMS
Changeable and Indexed.
You can change a value of a ceratain item in a
SYNTAX: dictionary by specifying the key Value and using the
Identifier = { Assignment operator “=”.
key1 : value1,
key2 : value2, SYNTAX:
key3 : value3 dictionary[key] = value
}
Ex code.
Ex code. studentOne = {
studentOne = { “name” : “elmarr”,
“name” : “elmarr”,
“course” : “BSIT”,
“course” : “BSIT”,
“age” : 15 “age” : 15
} }
studentTwo = {
“name” : “reymond”, studentOne[“name”] = “reymond”
“course” : “BSCs”,
“age” : 20
} print (studenOne)

print (studenOne)
print (studentTwo)
Name: Elmar Reymond A. Delac Cruz Page # 8
Contact No.: 0966-560-8740 Created by: Elmar

Dictionary LENGTH Dictionary DELETING ITEMS by POPITEM()


You can check the number of items (key pairs) in a popitem() deletes the last inserted item on the
Dictionary by using the len() function. dictionary.

SYNTAX: Syntax:
len(dictionary) dictionary.popitem()
Ex code. Ex code.
studentOne = { studentOne = {
“name” : “elmarr”, “name” : “elmarr”,
“course” : “BSIT”, “course” : “BSIT”,
“age” : 15 “age” : 15
} }

print (len(studentOne)) StudentOne.popitem()

print (studenOne )
Dictionary ADD ITEMS
You can add items on a dictionary just by assigning a
non-existent key value in the dictionary. Clearing a Dictionary
clear() deletes all the items in a Dictionary.
SYNTAX:
dictionary[key] = value SYNTAX:
Ex code. dictionary.clear()
studentOne = {
“name” : “elmarr”, Ex code.
“course” : “BSIT”, studentOne = {
“name” : “elmarr”,
“age” : 15
} “course” : “BSIT”,
“age” : 15
}
studentOne[“gender”] = “male”
StudentOne.clear()
print (studenOne )
print (studenOne )

Dictionary DELETING ITEMS by POP()


pop() deletes an item based on their key value. Copying a Dictionary
copy() copies the whole dictionary which can be
SYNTAX: assigned to a new dictionary.
dictionary.pop(key)
Ex code. SYNTAX:
studentOne = { dictionaryOne = {key1 : value, key2 : value2}
“name” : “elmarr”,
“course” : “BSIT”, dictionaryTwo = dictionaryOne.copy()
“age” : 15 Ex code.
} studentOne = {
“name” : “elmarr”,
StudentOne.pop(“name”) “course” : “BSIT”,
“age” : 15
print (studenOne ) }

studentTwo.copy()

print (studentTwo )
Name: Elmar Reymond A. Delac Cruz Page # 9
Contact No.: 0966-560-8740 Created by: Elmar

Getting ALL Keys in Dictionary Nested Dictionaries


keys() returns a list that contains all the keys inside A dictionary inside a dictionary.
your dictionary.
SYANTAX:
SYNTAX: dictionary1 = {
dictionary.keys() key1 : value1,
key2 : value2,
Ex code.
studentOne = { key3 : value3
“name” : “elmarr”, }
“course” : “BSIT”, dictionary2 = {
“age” : 15 key4 : value4,
}
key5 : value5,
print (studentOne.key() ) key6 : dictionary1
}
Getting ALL Values in Dictionary Ex code. Ex code.
values() returns a list that contains all the values sports = { sports = {
inside your dictionary. “sport1” : “Taekwondo” “sport1” : “Taekwondo”
“sport2” : “badminton” “sport2” : “badminton”
“sport3” : “E-sport” “sport3” : “E-sport”
SYNTAX:
} }
dictionary.values() studentInfo = { studentInfo = {
Ex code. “name” : “elmarr”, “name” : “elmarr”,
studentOne = { “course” : “BSIT”, “course” : “BSIT”,
“name” : “elmarr”,
“age” : 15, “age” : 15,
“course” : “BSIT”,
“age” : 15 “sports” : sports “sports” : sports
} } }

print (studentOne.values() )
print ( studentInfo) print ( studentInfo.get(“sport”))

List of Dctionaries
You can put a Dictionary inside a List, you can also Ex code.
sports = {
use indexing combined with get().
“sport1” : “Taekwondo”
“sport2” : “badminton”
SYNTAX: “sport3” : “E-sport”
dictionary1 = { }
key1 : value1, studentInfo = {
key2 : value2, “name” : “elmarr”,
key3 : value3 “course” : “BSIT”,
} “age” : 15,
dictionary2 = { “sports” : sports
key4 : value4, }
key5 : value5,
key6 : value6 print (
} studentInfo.get(“sport”).get(“sport1”) )
Identifier = [ dictionary1, dictionary2]
Ex code. Ex code.
studentOne = { studentOne = {
“name” : “elmarr”, “name” : “elmarr”,
“course” : “BSIT”, “course” : “BSIT”,
“age” : 15 “age” : 15
} }
studentTwo = { studentTwo = {
“name” : “reymond”, “name” : “reymond”,
“course” : “BSCs”, “course” : “BSCs”,
“age” : 20 “age” : 20
} }

students = [studentOne, studentTwo] students = [studentOne, studentTwo]

print ( students ) print ( students [0].get (“name”) )


Name: Elmar Reymond A. Delac Cruz Page # 10
Contact No.: 0966-560-8740 Created by: Elmar

10. Conditional Statements 13. IF-ELIF-ELSE Statements


A Statement that makes the program smarter, it Used when dealing with THREE OR MORE
makes the program decides on what to do in certain Conditions.
CONDITIONS. You also need to use conditional
SYNTAX:
operators to compare values inside a Conditional if valueOne == valueTwo:
Statement. Block to executed
elif valueOne == valueThree:
Conditional Statements Block to executed
IF Statements (1 Conditiona) else:
IF-ELSE Statement (2 Conditions) Block to executed
IF_ELIF-ELSE (3 or More Conditions)
Ex. Code:
NESTED Conditional Statements (Condition
grade = int( input (“Enter a grade: “))
after a Condition) if grade >= 75:
Conditional Operators print(“Excellent”)
Operators elif grade == 75:
== Equal print(“Good job”)
!= Not Equal else:
> Greater Than print (“You try your best”)
< Less Than
>= Greater Than or Equal
14. NESTED Conditional Statement
<= Less Than or Equal
Used when dealing with CONDITIONAL INSIDE A
CONDITION.
11. IF Statement
Used when dealing with ONE Condition. SYNTAX:
if valueOne == valueTwo:
SYNTAX: Block to executed
if valueOne == valueTwo: elif valueOne == valueThree:
Block to executed Block to executed
else:
Ex. Code:
Block to executed
age = int( input (“Enter your age: “))
if age >= 18: Ex. Code:
print( “You’re can vote”) register = str( input (“Are you enrolled in ERAD School? ”))
grade = int( input (“Enter a grade: “))
12. IF-ELSE Statement
Used when dealing with TWO Conditions. if register == “yes”:
if grade >= 75:
SYNTAX: print(“Excellent”)
if valueOne == valueTwo: elif grade == 75:
Block to executed print(“Good job”)
else: else:
Block to executed print (“You try your best”)

Ex. Code:
age = int( input (“Enter your age: “))
if age >= 18:
print(“You’re can vote”)
else:
print (“You’re too young”)
Name: Elmar Reymond A. Delac Cruz Page # 11
Contact No.: 0966-560-8740 Created by: Elmar

15. NOT Keyword COLLECTION Conditional Statement


Used to invert the condition value. Used to check an item if it’s in a collection (List and
Tuples).
SYNTAX:
if not ValueOne == valueTwo: SYNTAX:
list = [item1, item2, item3]
Ex. Code: if value in list:
opinion = str( input (“Do you breath? ”)) Block to execute
if not opinion == “yes”: else:
print( “You’re a living”) Block to execute
Ex. Code:
st
#remove the gun after 1 executing
16. LOGICAL Operators
bag = [“wallet, “gun”, “shirt”]
Used to include 2 or MORE Conditions in one line.
if “gun” in bag:
Logical Operators print( “Contraband”)
AND – BOTH CONDITION MUST BE TRUE. else:
OR – EITHER CONDITION MUST BE TRUE. print( “All clear”)
Ex. Code:
st
Ex. Code: #remove the gun & knife after 1 executing
#You have created an account where it have password of elmar123 and username of elmarr bag = [“wallet, “gun”, “shirt”, “knife”]
accountPassword = elmar123
if “gun” in bag or knife in bag:
accountUsername = elmarr
print( “Contraband”)
username = str( input (“Enter username: ”)) else:
password = str(input (“Enter password: “)) print( “All clear”)
if user == accountUsername and password == accountPassword:
print(“Access Granted”) 17. WHILE Loop
else: A Statement that will repeat a block of code as long
print (“Access Denied”)
as it’s condition is fulfilled.

Ex. Code: SYNTAX:


#Teacher say bring either floor wax or broom if you don’t bring anything you can’t get inside while value1 > value2:
#the room
block to execute
bringbroom = “yes”
bringfloorwax = “yes”
Ex. Code:
# infinite loop
broom = str( input (“Do you bring a broom? ”))
age = 12
floorwax = str(input (“Do you bring a floorwax? “))

if broom == bringbroom or floorwax == bringfloorwax: while age < 18:


print(“Get inside”)
else:
print ( “Your age is ” + str( age ) + “ you’re young”)
print (“You can go home”)

Ex. Code:
#finite loop
age = 12

while age < 18:


print ( “Your age is ” + str( age ) + “ you’re young”)
age = age +1

print ( “Your age is ” + str(age) + “ you’re in legal age”)


Name: Elmar Reymond A. Delac Cruz Page # 12
Contact No.: 0966-560-8740 Created by: Elmar

ELSE in WHILE Loop CONDITIONS in WHILE Loop


ELSE is added to the bottom of a while loop so that You can use any Conditional Statement inside a
it can execute code when the loop is done. WHILE Loop.
Ex. Code:
SYNTAAX:
i=1
while value1 > value2: while i < 2:
Block to execue answer = str( input ( “Do your crush love you too yes or no? ”) )
else: if answer == “no”:
Block to execute print (“Your awake”)
break
Ex. Code: else:
age = 12 print (“You need to wake”)

while age < 18: Ex. Code:


print ( “Your age is ” + str( age ) + “ you’re young”) numbers =[1, 2, 3, 4, 5, 6, 7, 8, 10]
age = age +1
else: i=0
print ( “Your age is ” + str(age) + “ you’re in legal age”)
while i < len(numbers):
if (numbers[i] % 2 == 0):
print (str(numbers[i]) + “ is even number”)
WHILE Loop in COLLECTIONS break
WHILE Loop can be used to access every item in a else:
COLLECTION (Lists & Tuples) Since it is indexed and print (str(numbers[i] + “ is odd number”)
ordered.
Ex. Code:
basket = [ apples, bananas, grapes, mangos]
i=0 18. Foor Loop
print (“The basket contain”) A Statement that is commonly used to iterate
through a collection or to execute a block of code in
while i <= 3: a certain amount of times.
print (basket[i])
i = i +1 FOR Loop in COLLECTIONS
FOR Loop can be used to access every item in a
COLLECTION (List & Tuples) in a vet easy way.
Ex. Code:
basket = [ apples, bananas, grapes, mangos]
SYNTAX:
i=0
for initialization in collection:
print (“The basket contain:”)
#Code to be execute
while i <= len(basket): Ex. Code:
print (basket[i]) fruits = [“banana”, “apple”, “orange”]
i = i +1
for x in fruits:
print(x)
BREAK Keyword in WHILE Loop
BREAK Keyword is used to stop the loop no matter
what the condition is.

Ex. Code:
#this is infinite loop

While True:
print (“Hello World!)
break #try to remove the break keyword
Name: Elmar Reymond A. Delac Cruz Page # 13
Contact No.: 0966-560-8740 Created by: Elmar

ELSE in For Loop RANGE()in FOR Loop


Else is added to the bottom of a for loop so that it Loops a set of code in a specified number of times.
can execute code when the loop is done.
PS: always plus 1 to the counter.
SYNTAX:
for identifier in collection: SYNTAX:
#code to be execute for identifier in range(counter):
else: #code to be executed
#code to execute
for identifier in range(initialization, counter):
Ex. Code: #code to be executed
fruits = [“banana”, “apple”, “orange”]
for x in fruits: Ex. Code: Ex. Code:
print (x)
else: for num in range(11): for num in range(1, 11):
print (“No more fruits”) print (num) print (num)

BREAK Keyword in FOR Loop NESTED FOR loop


BREAK Keyword is used to stop the loop earlier than A For Loop inside a For Loop commonly used to
its supposed to finish. iterate through a multi-dimensional collection.

Ex. Code:
fruits = [“banana”, “apple”, “orange”] Using RANGE in NESTED FOR Loop
for x in fruits: Ex. Code: Ex. Code:
print (x) vertical asterisk horizontal asterisk
break
for e in range(5): for e in range(5):
for y in range(5): for y in range(5):
CONDITIONS in FOR Loop print(“*”) print(“*”,end=””)
You can use any Conditional Statement inside a FOR
Loop.
Ex. Code: Ex. Code:
5 row & column asterisk
fruits = [“banana”, “apple”, “orange”, “avocado”, “ grapes”]
for x in fruits:
for e in range(5):
print (x)
for y in range(5):
if x == “avocado”:
print(“*”,end=””)
break
print()

Ex. Code:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Reading Multi – Dimensional Collections
for num in numberss: Using Nested For Loop
if num % 2 == 0:
Ex. Code: Ex. Code:
print (“Even numbe: ” + str(num))

petNames = [ petNames = [
[“Dog”,”Sam”], [“Dog”,”Sam”],
[“Dog”,”Staby”], [“Dog”,”Staby”],
[“Dog”, “Princess”], [“Dog”, “Princess”],
[“Cat”,”Cloie”], [“Cat”,”Cloie”],
[“Cat”, “SnowBell”] [“Cat”, “SnowBell”]
] ]
for listPet in petName s; for listPet in petName s;
for x in listPet; for x in listPet;
print(i) print(i)
print()

You might also like