Welcome to zeroslash.io

There's nothing to show here but you can use the link below to go to the main website.

Zeroslash Python hands-on tutorial

Gusto mo bang magsimula na sa programming?

Python

Python + Juniper Network Automation lab

This is a Network Automation lab using Vagrant.

If you don't have a Vagrant lab yet, you can follow the steps in this blog: How To Install Virtualbox and Vagrant For Your Virtual Lab.

To set up this lab, copy + paste the below configuration into your Vagrantfile.

This lab is based from Juniper's vqfx10k-vagrant labs but I made a simpler version so it's easier to get started.

The original labs relied on vagrant provisioning (it automatically sets up the initial configuration of the devices). However, their provisioning required WSL (Windows Subsystem for Linux) for those who use Windows.

I'm avoiding that dependency since this lab was meant to be simple. Besides, the initial configuration required for the vQFX in this lab is just 1 IP address which should be quick. Just follow the required configuration below.


Make sure to bring up the lab first using vagrant up

$ vagrant up


You can check the status of the devices once this is done (optional).

$ vagrant status


Login to the vqfx device.

$ vagrant ssh vqfx


Configure the ip address 10.1.2.1 on interface xe-0/0/0.

NOTE: We also need to remove the preconfigured dhcp setting so we can assign an IP address.

vagrant@vqfx-re> edit
Entering configuration mode

{master:0}[edit]
vagrant@vqfx-re# set interfaces xe-0/0/0 unit 0 family inet address 10.1.2.1/24

{master:0}[edit]
vagrant@vqfx-re# delete interfaces xe-0/0/0 unit 0 family inet dhcp

{master:0}[edit]
vagrant@vqfx-re# commit
configuration check succeeds
commit complete

{master:0}[edit]
vagrant@vqfx-re# exit
Exiting configuration mode

{master:0}
vagrant@vqfx-re>

The Vagrant lab setup is now complete.

Below are videos to use as reference in setting up Python for Juniper Network Automation.

A Tour of Python

by Zeroslash

Subukan ang Python / Programming para malaman kung magugustuhan mo ito

Ang mga sumusunod ay mga Python topics na susundan mo lang step-by-step para ma-experience mo ang programming.

Back to Main

Install Python

Download Python from the official site: Download Python
Normally, makikita mo na ang latest version sa mismong download button.

NOTE: Kung ikaw ay naka Mac OS o kaya naman ay Linux, most likely ay installed na ang Python sa computer mo by default.

For Windows users, pagka-launch ng installation wizard kailangan mo i-check yung option na Add Python 3.x to PATH. Kapag wala ang option na ito, maaaring magkaproblema sa pagamit ng Python command (hindi mahahanap ni Windows kung asaan yung Python). Tapusin ang installation wizard sa pamamagitan ng pag-click ng next, etc.

Back to Main

Test Python

For Windows users, buksan ang Command Prompt (or pwede rin PowerShell) na program at i-type and command na python:

C:\Users\your_username> python

NOTE: Kung ikaw ay naka Mac OS o kaya naman ay Linux, same lang din ang steps. Gagamitin mo lang kung ano yung terminal program ng OS mo (ex. Terminal App ng Mac OS)

Mapapansin mo na nagbago ang prompt pagkatapos mo i-type ang command na python. Ganito ang itsura nya:

>>>

Kapag hindi nag-error at nakita mo itong prompt na ito, ibig sabihin successfully installed na ang Python sa computer mo.

NOTE: Sa itaas bago yung prompt pinapakita din yung version ng Python. Siguraduhing Python 3 (3.x.x) ang gamit mo.

Sa ngayon, nasa loob tayo ng Python interactive interpreter. Pero test lang ito, so skip muna natin ang paggamit ng interactive interpreter for now. Type exit() para mag-exit.

>>> exit()

Ngayon para sa classic example na hello world, gumawa tayo ng file kung saan natin ilalagay ang Python code natin.

Para mas madali, mag-create ka ng file dun sa mismong folder na pinapakita sa prompt ng terminal mo. For example, sa Windows Command Prompt maaaring ganito sya.

C:\Users\your_username>

In this case, kung ang username mo ay john then pumunta ka sa folder na Users > john then mag-create ng file dun.

NOTE: Pwede kang gumamit ng kahit anong text editor na gusto mo. Kahit notepad pwede pero may mga mas maayos na pwede for programming kagaya ng Sublime text or even Notepad++ pwde na for simple code editing.

Bigyan mo ng filename na mytest.py. Pagkatapos ilagay ang code na ito sa file:

print("hello world!")

Sa code na ito, ginamit natin ang print function para mag-display ng text / words sa screen.

I-save ang file pagkatapos ay i-run yung program sa terminal.

> python mytest.py
hello world!

For Windows, ganito yung example kung sa Command Prompt.

C:\Users\your_username> python mytest.py
hello world!

Congratulations sa first Python program mo :)

NOTE: For the rest of the topics, ang gagamitin ko nalang na command line prompt sa examples is simply >.

So regardless kung Windows, Mac OS or Linux gamit mo, ganito ang itsura ng magiging examples ko para sa lahat.

> python mytest.py

Back to Main

Terms

May mga ilang basic terminology na paulit-ulit natin gagamitin throughout this series of topics. Nabanggit ko na sila sa previous topic sa pag-test ng Python. Pero para malinaw, gusto ko i-explain ang mga ito bago tayo magpatuloy.

Program - usually bawat topic may gagawin tayong isang program.

> python mytest.py <- dito yung mytest.py yung program natin

Code - Magsusulat tayo ng code para buuin yung program. Ito yung magiging laman ng bawat file na part ng program natin.

print("hello world!") <- ito ay example ng code

Function - Meron tayong dedicated topic para lamang sa functions. Pero since gagamitin na natin sila sa mga examples natin, mas maigi na mayroon tayong basic idea dito. Ang function ay code lang din na kapag ginamit mo, mageexecute sya ng specific na task. May iba't ibang functions tayong gagamitin at may kanya-kanya silang functionality. Ito ay mga functions ni Python na built-in na sa kanya. Marami sa kanila ay kailangan pasahan ng data para i-process.

print("hello world!") <- ang print() ay isang example ng function

Ngayon syempre hindi ko mapapagkasya sa tutorial na ito ang napakarami pang mga programming concepts. Kung kinakailangan, andyan naman si Google, si Yahoo, or si DuckDuckGo.

If you're looking for a place to ask questions, o kaya naman ay interesado ka sa discussions about Python or programming in general, pwede kang sumali sa FB community namin: Programming and I.T. Automation Philippines

Back to Main

Comments

Minsan kinakailangan natin maglagay ng description or additional information about sa code natin. Magagawa natin ito sa pamamagitan ng comments.

Buksan uli ang mytest.py at i-edit ito. Idagdag ang mga comments kasunod ng print at sa ibaba nito.

print("hello world!") # Output to screen
# All comments are ignored.

Pag i-run mo uli yung program dapat walang magbago.

> python mytest.py
hello world!

NOTE: Maramin tayong gagawin na code examples all throughout our topics. I encourage you na i-type lahat ng code para ma-practice mo talaga ang coding. Naglalagay din ako ng comments sa code examples kagaya ng ginawa natin dito. Nasa sayo na kung gusto mo i-type pati ang comments o hindi.

Back to Main

Accept user input

Typically, ang mga programs ay tatanggap ng data as input, will process yung data, then finally may ibibigay na result bilang kanyang output.

Gumawa ng file at bigyan ito ng filename na input.py. Pagkatapos ilagay ang code na ito sa file:

import sys

firstname = sys.argv[1] # captures 1st argument
lastname = sys.argv[2] # captures 2nd argument

print(firstname)
print(lastname)

Skip muna natin yung code for import sa ngayon. Dadaanan natin yan in a later topic.

Ang focus natin dito is yung sys.argv. Ito yung paraan natin para makakuha ng input.

Ngayon i-run ang program at bigyan ito ng arguments na (1) Naruto at (2) Uzumaki

> python input.py Naruto Uzumaki
Naruto
Uzumaki

Back to Main

Accept user input interactively

Pwedeng mag-accept ng input from user in an interactive way. Ibig sabihin, manghihingi ng input yung program sayo in real-time. Pwde mo rin isipin na para bang naguusap lang kayo.

Gumawa ng file at bigyan ito ng filename na askdetails.py. Pagkatapos ilagay ang code na ito sa file:

email = input("What is your email address? ")
phone = input("What is your phone number? ")

print("Email:", email)
print("Phone:", phone)

Ngayon i-run yung program at bigyan ito ng example data para sa hinihingi nyang input.

> python askdetails.py
What is your email address? [email protected]
What is your phone number? 7446624
Email: [email protected]
Phone: 7446624

Back to Main

Values

In simple terms, ang value ay data. Bumubuo tayo ng programs to do something with data.

Sa hello world example natin, yung "hello world!" is considered a value.

print("hello world!")

Gumawa ng file at bigyan ito ng filename na mission.py. Pagkatapos ilagay ang code na ito sa file:

print("Mission:", "Protect Konoha")
print("Team:", 7)
print("Success?:", True)

Dito sa example na ito, meron tayong iba't ibang values kagaya ng "Protect Konoha", 7, and True.

In fact, kahit yung "Mission:", "Team:", and "Success?:" are all values.

Pagka-run mo ng program ganito dapat yung output.

> python mission.py
Mission: Protect Konoha
Team: 7
Success?: True

Back to Main

Variables

Mas madalas ang data is hindi 1-time use lang. Usually ginagamit ito multiple times sa program. Hindi ba mas maganda kung pwede mong i-save ang isang value para magamit ito later on?

Gumawa ng file at bigyan ito ng filename na mission-with-variables.py. Pagkatapos ilagay ang code na ito sa file:

mission = "Protect Konoha"
team = 7
is_success = True

print("Mission:", mission)
print("Team:", team)
print("Success?:", is_success)

Let's use mission as an example. Ang "Protect Konoha" na value is naka-assign na ngayon sa variable na pinangalanan nating mission.

Ngayon pagdating dun sa print("Mission:", mission), the variable mission is mapapalitan ng "Protect Konoha".

Pag i-run mo uli yung program dapat wala itong pinagbago sa previous example natin na mission.py.

> python mission-with-variables.py
Mission: Protect Konoha
Team: 7
Success?: True

Wala itong pinagbago dahil effectively and mga variables ay mapapalitan lang ng kung ano man yung value na naka-assign sa kanila.

Back to Main

Types

Sa mission at mission-with-variables examples natin, iba iba yung ginamit natin na values. Dahil may iba't ibang klase ng data, binibigyan din natin sila ng classification sa loob ng programs natin. Ito yung tinatawag na types. Bawat value ay kabilang sa isang klase ng type.

Gumawa ng file at bigyan ito ng filename na mission-with-types.py. Pagkatapos ilagay ang code na ito sa file:

mission = "Protect Konoha"
team = 7
is_success = True

print("mission:", type(mission) ) # String
print("team:", type(team) ) # Integer (a number)
print("is_success:", type(is_success) ) # Boolean (true/false)

Ginagamit natin ang type() function para makita natin kung ano ang type ng isang value.

NOTE: Kahit na ginamit natin ang type() sa variables dito sa example, makukuha parin natin yung type ng mismong value assigned dun sa variable.

Pagka-run mo ng program ganito dapat yung output.

> python mission-with-types.py
mission: <class 'str'>
team: <class 'int'>
is_success: <class 'bool'>

Back to Main

Strings

Nakailang beses narin natin ginamit ang strings sa mga example natin. Ang strings ay ginagamit natin para sa mga "text" na klase ng data (e.g. words, sentences, etc.).

Ang basic way sa paggawa ng string is ipaloob ito sa quotes. Pwedeng gumamit ng single or double quotes. Pareho itong valid.

Gumawa ng file at bigyan ito ng filename na string-quotes.py. Pagkatapos ilagay ang code na ito sa file:

# print string values
print('using single quotes')
print("using double quotes")

# assign string values to a variable
single = 'using single quotes'
double = "using double quotes"

print("single:", single)
print("double:", double)

Pagka-run mo ng program ganito dapat yung output.

> python string-quotes.py
using single quotes
using double quotes
single: using single quotes
double: using double quotes

Back to Main

Numbers

Sa topic ng types meron tayong example ng number. In particular, ito ay yung integer. Isa ito sa common na ma-eencounter na type ng number sa programming. Meron din isa pang type na common din kagaya ng integer at ito ay yung float. Ito ay ginagamit for floating-point numbers.

Importante na mayroon tayong dedicated types for numbers. In fact, importante talaga na mayroon tayong types para sa lahat ng values. Ipagpalagay natin na mayroon tayong variables a and b. Paano malalaman kung compatible ang dalawa at pwede silang i-add? Yun ay mangyayari lamang kung pareho silang numbers. For example, a + b will work if both are integer types.

Gumawa ng file at bigyan ito ng filename na numbers.py. Pagkatapos ilagay ang code na ito sa file:

print(100) # an integer
print(1.0) # a float

intA = 10
intB = 5
print(intA + intB) # add two integers

floatA = 6.5
floatB = 3.5
print(floatA + floatB) # add two floats

Pagka-run mo ng program ganito dapat yung output.

> python numbers.py
100
1.0
15
10.0

Back to Main

Arithmetic operators

Nadaanan na natin ang mga number types. Ngayon ano ang pwede natin gawin sa kanila? Syempre, ineexpect natin that we can do Math with them. Simple lang naman, yung nagagawa natin sa calculator, kaya din natin gawin sa loob ng program natin.

Nagawa na natin ang addition sa numbers example natin. Ginamit natin ang + operator para i-add ang mga integers pati narin ang floats. Isa lang ito sa mga arithmetic operators na pwede natin gamitin.

Gumawa ng file at bigyan ito ng filename na arithmetic-operators.py. Pagkatapos ilagay ang code na ito sa file:

print(5 + 4) # Addition
print(9 - 7) # Subtraction
print(7 * 8) # Multiplication

# True division - result is always a float
print(12 / 5) # with remainder
print(12 / 3) # this has no remainder but still a float

# Floor division - result is always an integer
print(12 // 5) # rounds off the result (round down to lower value)
print(12 // 3)

Pagka-run mo ng program ganito dapat yung output.

> python arithmetic-operators.py
9
2
56
2.4
4.0
2
4

Back to Main

Assignment operators

Nagkaroon na tayo ng idea about arithmetc operators, it's time to introduce another kind of operator. Actually, ginamit na natin sya nung una pa lang sa input example, at mas lalo na nung mission-with-variables example. Ito ay yung = operator (assignment operator).

firstname = sys.argv[1] # captures 1st argument
lastname = sys.argv[2] # captures 2nd argument

mission = "Protect Konoha"
team = 7
is_success = True

Ang purpose ng mga assignment operators ay mag-assign ng value sa variable. Sa examples natin so far, ang ginagawa lang ng = operator is kunin yung value sa kanan nito, at i-assign sya sa variable sa kaliwa nito.

NOTE: Maaaring ang nasa kanan ng = operator is another variable. Kagaya sa example natin na firstname = sys.argv[1]. In this case, kung ano man ang naka-assign na value sa sys.argv[1], yun din ang mapupunta sa firstname.

Marami pang ibang klase ng assignment operator. Ang pinaka common ay yung pinagsamang assignment at arithmetic operator.

Gumawa ng file at bigyan ito ng filename na update-variable.py. Pagkatapos ilagay ang code na ito sa file:

import sys

number_from_user = sys.argv[1] # accept a number

# make sure we have a number so we can do math
number = int(number_from_user) # convert to integer

number += 1000 # add 1000 and put the result back to number
print(number)

number *= 5 # multiply by 5 and put the result back to number
print(number)

number -= 100 # subtract 100 and put the result back to number
print(number)

number //= 2 # divide by 2 and put the result back to number
print(number)

Ngayon i-run ang program at bigyan ito ng argument na number. For example:

> python update-variable.py 10
1010
5050
4950
2475

Subukang bigyan ito ng iba pang number.

> python update-variable.py 90
...
> python update-variable.py 550
...

Back to Main

Booleans

Maraming pagkakataon na kailangan natin sabihin kung totoo o hindi ang isang bagay. Pwede natin ito i-represent as True / False sa program natin. Ito yung tinatawag natin na boolean value.

Medyo flexible din ang boolean kasi pwede rin ito i-apply in anything that can only have 2 states such as:

  • yes / no

  • active / inactive

  • enabled / disabled

Una natin nakita ang boolean value sa mission example natin.

print("Mission:", "Protect Konoha")
print("Team:", 7)
print("Success?:", True)

Pero tska lang natin nakita na boolean type ito nung pinagusapan na natin ang types.

is_success = True
...
print("is_success:", type(is_success) ) # Boolean (true/false)

is_success: <class 'bool'>

Para sa example natin for this topic, gagamit tayo ng isang function na ang result is boolean.

Gumawa ng file at bigyan ito ng filename na mission-type-check.py. Pagkatapos ilagay ang code na ito sa file:

mission = "Protect Konoha"
team = 7
is_success = True

# Expected to be True
mission_string = isinstance(mission, str) # is it a string?
team_integer = isinstance(team, int) # is it an integer?
is_success_bool = isinstance(is_success, bool) # is it a boolean?

print(mission_string)
print(team_integer)
print(is_success_bool)

# Expected to be False
mission_integer = isinstance(mission, int) # is it an integer?
team_float = isinstance(team, float) # is it a float?
is_success_string = isinstance(is_success, str) # is it a string?

print(mission_integer)
print(team_float)
print(is_success_string)

Ang focus natin dito is yung result lang ng isinstance function na boolean.

Pagka-run mo ng program ganito dapat yung output.

> python mission-type-check.py
True
True
True
False
False
False

Back to Main

Logical operators

Bagamat ang boolean values ay simple kung ikukumpara sa ibang types, it becomes quite powerful kung gagamitin ito with logical operators.

Ang logical operators ay isang pang group ng operators na ginagamit specifically with boolean values.

Gumawa ng file at bigyan ito ng filename na logical-operators.py. Pagkatapos ilagay ang code na ito sa file:

# AND
print(True and True) # True if both are True
print(True and False) # False if at least one is False

# OR
print(False or False) # False if both are False
print(False or True) # True if at least one is True

# NOT (simply inverts the value)
print(not True)
print(not False)

Pagka-run mo ng program ganito dapat yung output.

> python logical-operators.py
True
False
False
True
False
True

Back to Main

Lists

So far, ang mga types pa lang na nagamit natin is string, integer, float at boolean. Kung mapapansin mo, lahat sila can only represent a single value. Papano naman kung mayroon kang group of 10 strings? or 100 integers? or 1,000 floats?

Minsan kailangan natin ng way para i-represent ang isang group or collection of values. For example, mayroon tayong list of students. Bawat entry is yung full name ng student. Pwede natin gawan ng string ang bawat full name at ipaloob lahat sa isang list.

Gumawa ng file at bigyan ito ng filename na ninja-academy.py. Pagkatapos ilagay ang code na ito sa file:

# lists are created using square brackets []
students = ['Uzumaki, Boruto', 'Uchiha, Sarada', 'Mitsuki',
'Nara, Shikadai', 'Akimichi, Chocho', 'Yamanaka, Inojin']

print(students)

# each value inside a list can be accessed through its index number
print(students[0]) # index numbers starts at 0
print(students[1])
print(students[3])
print(students[-1]) # use negative index numbers to start at the end

NOTE: Maraming concept sa computers at programming ang nagsisimula magbilang sa 0 instead of 1. So ang first item is 0, second is 1, so on and so forth.

Pagka-run mo ng program ganito dapat yung output.

> python ninja-academy.py
['Uzumaki, Boruto', 'Uchiha, Sarada', 'Mitsuki', 'Nara, Shikadai', 'Akimichi, Chocho', 'Yamanaka, Inojin']
Uzumaki, Boruto
Uchiha, Sarada
Nara, Shikadai
Yamanaka, Inojin

Back to Main

Modifying lists

Ang groups of data pwedeng dumami, pwedeng kumonti, at pwedeng ma-update. For example, at any point in time, pwedeng madagdagan ang students sa school. Also, any one of them can also update their school records.

So kung meron tayong group or collection of values gaya ng list, kailangan din natin ng way para i-modify ito.

Gumawa ng file at bigyan ito ng filename na modify-ninja-academy.py. Pagkatapos ilagay ang code na ito sa file:

students = ['Uzumaki, Boruto', 'Uchiha, Sarada', 'Mitsuki',
'Nara, Shikadai', 'Akimichi, Chocho', 'Yamanaka, Inojin']

# add an item to the end of the list
students.append('Lee, Metal')
print(students)

# add an item to a specific position (use index number)
students.insert(0, 'Kaminarimon, Denki')
print(students)

# modify a specific item in the list (use index number)
students[0] = 'Yuino, Iwabe'
print(students)

# pop() removes the last item by default
students.pop()
print(students)

# pop() can optionally remove a specific item (use index number)
students.pop(0)
print(students)

# del is another way to delete an item but it's not specific to lists
del students[0]
print(students)

Pagka-run mo ng program ganito dapat yung output.

> python modify-ninja-academy.py
['Uzumaki, Boruto', 'Uchiha, Sarada', 'Mitsuki', 'Nara, Shikadai', 'Akimichi, Chocho', 'Yamanaka, Inojin', 'Lee, Metal']
['Kaminarimon, Denki', 'Uzumaki, Boruto', 'Uchiha, Sarada', 'Mitsuki', 'Nara, Shikadai', 'Akimichi, Chocho', 'Yamanaka, Inojin', 'Lee, Metal']
['Yuino, Iwabe', 'Uzumaki, Boruto', 'Uchiha, Sarada', 'Mitsuki', 'Nara, Shikadai', 'Akimichi, Chocho', 'Yamanaka, Inojin', 'Lee, Metal']
['Yuino, Iwabe', 'Uzumaki, Boruto', 'Uchiha, Sarada', 'Mitsuki', 'Nara, Shikadai', 'Akimichi, Chocho', 'Yamanaka, Inojin']
['Uzumaki, Boruto', 'Uchiha, Sarada', 'Mitsuki', 'Nara, Shikadai', 'Akimichi, Chocho', 'Yamanaka, Inojin']
['Uchiha, Sarada', 'Mitsuki', 'Nara, Shikadai', 'Akimichi, Chocho', 'Yamanaka, Inojin']

Back to Main

Tuples

Ang tuple ay kagaya rin ng list (sabihin nalang natin na mag-pinsan sila). Ang kaibahan lang is hindi mo mababago ang laman ng tuple. Maaari mong makita ang laman nito, pero hindi mo na pwede baguhin kung ano ang nilagay sa tuple nung ginawa ito.

Gumawa ng file at bigyan ito ng filename na ninja-teams.py. Pagkatapos ilagay ang code na ito sa file:

# tuples are usually created using parentheses ()
# although the parentheses are optional, better stick with them for now
team7 = ('Uzumaki, Boruto', 'Uchiha, Sarada', 'Mitsuki')
team10 = ('Nara, Shikadai', 'Akimichi, Chocho', 'Yamanaka, Inojin')

# each value inside a tuple can be accessed through its index number
print(team7[0]) # index numbers starts at 0
print(team10[2])
print(team7[-1]) # use negative index numbers to start at the end

Pagka-run mo ng program ganito dapat yung output.

> python ninja-teams.py
Uzumaki, Boruto
Yamanaka, Inojin
Mitsuki

Nabanggit ko kanina na hindi na pwedeng baguhin ang nilagay sa tuple.

Buksan ulit ang file na ninja-teams.py at idagdag ang code na ito sa pinakababa.

del team10[1] # delete an item from tuple

Subukang i-run uli yung program at tingnan kung ano ang magiging result nito.

> python ninja-teams.py

Back to Main

Dictionaries

Nakita natin sa lists and tuples ang kakayanan na mag-store ng maraming values. Nakita rin natin ang bawat item is identified using index numbers at ito yung way para ma-access natin ang isang item sa loob nito (ex. mylist[0], mylist[1], mylist[2]).

Yun nga lang, minsan hindi helpful yung kukuha ka ng values sa pamamagitan ng number. Hindi lahat ng data ay bagay sa ganitong approach. At hindi rin lahat kailangan ng numbering para sa pagkakasunod-sunod. Minsan kailangan natin ng something more descriptive compared sa number.

Sa ganitong pagkakataon, pwede tayong gumamit ng dictionary. Sa dictionary, maaari tayong gumamit ng mas meaningful na pang-identify sa value na inii-store natin. For example, pwede tayong gumamit ng string para sa index gaya nito:

mydictionary['first_name']

Gumawa ng file at bigyan ito ng filename na kage.py. Pagkatapos ilagay ang code na ito sa file:

# dictionaries are created using curly brackets {}
kages = { 'Hokage': 'Naruto',
'Mizukage': 'Chojuro',
'Raikage': 'Darui',
'Kazekage': 'Gaara',
'Tsuchikage': 'Kurotsuchi'
}

print(kages)

print(kages['Hokage'])
print(kages['Kazekage'])

Bawat item within the dictionary is a key-value pair (key: value) kung saan ang key ay yung ginagamit na index. Through the key makukuha natin yung corresponding value nya.

Pagka-run mo ng program ganito dapat yung output.

> python kage.py
{'Hokage': 'Naruto', 'Mizukage': 'Chojuro', 'Raikage': 'Darui', 'Kazekage': 'Gaara', 'Tsuchikage': 'Kurotsuchi'}
Naruto
Gaara

Back to Main

Modifying dictionaries

Gaya ng list, pwede rin natin i-modify ang laman ng dictionary.

Gumawa ng file at bigyan ito ng filename na modify-kage.py. Pagkatapos ilagay ang code na ito sa file:

kages = { 'Hokage': 'Naruto',
'Mizukage': 'Chojuro',
'Raikage': 'Darui',
'Kazekage': 'Gaara',
'Tsuchikage': 'Kurotsuchi'
}

print(kages)

kages.pop('Hokage') # delete
print(kages)
# Now the key 'Hokage' doesn't exist anymore

kages['Hokage'] = 'Tsunade' # add item
print(kages)
# Now the key 'Hokage' exists again

kages['Hokage'] = 'Kakashi' # update existing key with a new value
print(kages)

# del can work on dictionaries too
del kages['Hokage']
print(kages)

NOTE: Mapapansin mo na walang pinagkaiba ang pag-add ng bagong item sa dictionary at sa pag-update nito. Lahat ay depende lang kung existing na yung key or hindi pa.

Pagka-run mo ng program ganito dapat yung output.

> python modify-kage.py
{'Hokage': 'Naruto', 'Mizukage': 'Chojuro', 'Raikage': 'Darui', 'Kazekage': 'Gaara', 'Tsuchikage': 'Kurotsuchi'}
{'Mizukage': 'Chojuro', 'Raikage': 'Darui', 'Kazekage': 'Gaara', 'Tsuchikage': 'Kurotsuchi'}
{'Mizukage': 'Chojuro', 'Raikage': 'Darui', 'Kazekage': 'Gaara', 'Tsuchikage': 'Kurotsuchi', 'Hokage': 'Tsunade'}
{'Mizukage': 'Chojuro', 'Raikage': 'Darui', 'Kazekage': 'Gaara', 'Tsuchikage': 'Kurotsuchi', 'Hokage': 'Kakashi'}
{'Mizukage': 'Chojuro', 'Raikage': 'Darui', 'Kazekage': 'Gaara', 'Tsuchikage': 'Kurotsuchi'}

Back to Main

Comparison operators

Isa sa mga common na requirement kapag gumagawa ng programs is yung pag-kumpara ng 2 values. For example, kailangan mo i-test kung magkapareho or match ba ang 2 strings or numbers, o kaya naman ay pag-kumpara ng 2 numbers kung alin ang mas mataas.

Kapag kailangan natin mag-kumpara ng values gagamit tayo ng comparison operators.

Gumawa ng file at bigyan ito ng filename na comparison-operators.py. Pagkatapos ilagay ang code na ito sa file:

print(5 == 4) # equal? (integers)
print(9 > 7) # greater than?
print(7 < 8) # less than?

print(5 != 4) # not equal?
print(7 >= 9) # greater than or equal to? (integers)
print(7 <= 8) # less than or equal to? (integers)

ninja = 'Shinobi'
print(ninja == 'Shinobi') # equal? (strings)

print(5.1 >= 5.0) # greater than or equal to? (floats)
print(5.1 <= 5.1) # less than or equal to? (floats)

Kung mapapansin mo, ang comparison operators ay sumasagot sa tanong na yes / no lang ang sagot. Dahil dito, maihahalintulad natin sila sa logical operators kung saan pareho silang boolean ang result.

Pagka-run mo ng program ganito dapat yung output.

> python comparison-operators.py
False
True
True
True
False
True
True
True
True

Back to Main

Membership operators

Kung mayroon tayong group or collection of values kagaya ng lists, tuples or dictionaries, may mga pagkakataon na kakailanganin nating alamin kung nag-eexist ba ang isang value sa loob nito.

Dito natin magagamit ang membership operators. Kaya nitong i-check kung "member" ba ang isang value ng isang group. Basically, para lang itong simple na search functionality.

Kagaya ng nakaraan nating topic na comparison operators, sumasagot din ito sa tanong na yes / no lang ang sagot - and yes, boolean din ang kanyang result.

Napapansin mo na ba ang trend? Ang boolean value na result ng mga ganitong operators is importanteng bagay na kailangan natin tandaan dahil malaking part ito sa mga susunod na topics.

Gumawa ng file at bigyan ito ng filename na ninja-team-directory.py. Pagkatapos ilagay ang code na ito sa file:

# search a tuple containing integers
assigned_teams = (7, 15)
print(15 in assigned_teams)

# search a list containing strings
available_teams = ['5', '10']
print('5' in available_teams) # the opposite of in

# simply searching a dictionary is searching against its keys
active_teams = {
'5': ('Lee, Metal', 'Yuino, Iwabe', 'Kaminarimon, Denki'),
'7': ('Uzumaki, Boruto', 'Uchiha, Sarada', 'Mitsuki'),
'10': ('Nara, Shikadai', 'Akimichi, Chocho', 'Yamanaka, Inojin'),
'15': ('Suzumeno, Namida', 'Izuno, Wasabi', 'Kurogane, Tsubaki')
}
print(available_teams[0] in active_teams)

Pagka-run mo ng program ganito dapat yung output.

> python ninja-team-directory.py
True
False
True

Back to Main

If statements

Sa logical-operators example natin, nakita natin kung paano mag-test gamit ang boolean logic such as:

  • True and True = True

  • False or True = True

  • not True = False

Sa comparison-operators example naman, nakita natin paano mag-test for equality (or non-equality) at kung paano gamitin ang greater than at less than.

At sa previous topic natin about membership operators, nakita natin kung paano mag-test kung ang isang value ay part ng isang group or hindi.

Nalaman natin na lahat sila ay nag-pproduce ng boolean result. Pero hindi dyan nagtatapos ang storya ng mga kapaki-pakinabang na operators natin. Most of the time, ang mga ganitong klase ng tests na may result na True or False ay ginagamit natin along with if statements.

Ang if statements ay binibigyan tayo ng opportunity para gumawa ng hakbang base sa boolean result. If something is True, ano ngayon ang gagawin? Kung False naman, ano mangyayari?

Gumawa ng file at bigyan ito ng filename na mission-ranks.py. Pagkatapos ilagay ang code na ito sa file:

NOTE: First time natin gagamit ng code na may identation. Ang code na nakapaloob sa if / elif / else ay kailangan indented. For consistency, i-indent mo using 4 spaces at huwag gumamit ng tab para makaiwas sa indentation errors.

import sys

rank_input = sys.argv[1]
mission_rank = rank_input.upper() # convert to uppercase

ninja_mission_ranks = ('S', 'A', 'B', 'C', 'D')

# Ensure input is a valid mission rank
if mission_rank in ninja_mission_ranks:
# If True
print("You entered a valid mission rank")

else:
# If False
print("Invalid mission rank")
print("Exiting...")
exit()

# Use if with any number of elif statements
# to support muliple True conditions
if mission_rank == 'D':
print("Assign to Genin")

elif mission_rank == 'C':
print("Assign to experienced Genin or Chunin")

elif mission_rank == 'B':
print("Assign to experienced Chunin")

elif mission_rank == 'A':
print("Assign to Jounin")

elif mission_rank == 'S':
print("Assign to experienced Jounin")

else:
# The first if else statement above already ensures valid inputs,
# so this else part is a duplicate of effort.
# But if you ever use if with elif statements like this example,
# include an else statement to cover unsupported/invalid options.
print("Unsupported mission rank")

Ngayon i-run ang program at bigyan ito ng argument na letter (a valid mission rank). For example:

> python mission-ranks.py a
You entered a valid mission rank
Assign to Jounin
> python mission-ranks.py b
You entered a valid mission rank
Assign to experienced Chunin
> python mission-ranks.py c
You entered a valid mission rank
Assign to experienced Genin or Chunin

Back to Main

While loops

May mga pagkakataon na kailangan natin magsagawa ng tasks for as long as something is True. Maaari natin paulit-ulitin ang isang part ng program ngunit sa ilalim lamang ng isang condition.

Maari tayong gumamit ng while loop para sa ganito. Similar ang while loop sa if statements kung saan kailangan din nito ng boolean result at indented din ang nakapaloob na code dito.

while <your_condition>: # is condition True or False?
<tasks_to_be_done_if_condition_is_true>
...

Importante ang condition na ito para ma-set natin kung anong rules ang kailangan masunod para umulit yung task. At kung hindi na nya ma-meet yung condition, kailangan na nyang tumigil.

Gumawa ng file at bigyan ito ng filename na countdown.py. Pagkatapos ilagay ang code na ito sa file:

import sys

number_from_user = sys.argv[1]
n = int(number_from_user) # convert to integer

while n >= 1: # the limit is 1
print(n)
n -= 1 # keep decrementing by 1

Ngayon i-run ang program at bigyan ito ng argument na number. For example:

> python countdown.py 3
3
2
1
> python countdown.py 5
5
4
3
2
1

Back to Main

For loops

Nadaanan na natin ang iba't ibang paraan kung paano i-group ang mga values kagaya ng paggamit ng lists. Isa sa mga pinaka-common na ginagawa with these groups or collection of values is to go through each item na nakapaloob dito. So pwede natin i-process ang bawat item.

Maari tayong gumamit ng for loop para sa ganito. Gaya ng while loops, indented din ang nakapaloob na code dito. Ang kaibahan lang, since medyo iba ang goal ng for loop, kailangan natin ibigay ang mga sumusunod:

  1. group or collection of values (ex. list)

  2. a temporary variable

for x in my_list:
<tasks_to_be_done_for_each_item> # do something with x
...

Ang temporary variable (in this case x) is yung way para makuha yung value ng bawat item, habang iniisa-isa ito ng for loop. Gaya ng normal na variable, ikaw ang bahala pumili ng pangalan nito.

Gumawa ng file at bigyan ito ng filename na tailed-beast.py. Pagkatapos ilagay ang code na ito sa file:

# a list with strings representing CSV data
bijuu_data = [
'Shukaku,1,Gaara',
'Matatabi,2,Yugito Nii',
'Isobu,3,Yagura Karatachi',
'Son Goku,4,Roshi',
'Kokuo,5,Han',
'Saiken,6,Utakata',
'Chomei,7,Fu',
'Gyuki,8,Killer Bee',
'Kurama,9,Naruto Uzumaki'
]

for x in bijuu_data: # x holds each item in the list one at a time
data = x.split(',') # split the string in every comma ','
#print(data) # uncomment this to see that split() produces a list
print("number of tails:", data[1])
print(" Bijuu:", data[0])
print(" Jinchuriki:", data[2])

Pagka-run mo ng program ganito dapat yung output.

> python tailed-beast.py
number of tails: 1
Bijuu: Shukaku
Jinchuriki: Gaara
number of tails: 2
Bijuu: Matatabi
Jinchuriki: Yugito Nii
number of tails: 3
Bijuu: Isobu
Jinchuriki: Yagura Karatachi
number of tails: 4
Bijuu: Son Goku
Jinchuriki: Roshi
number of tails: 5
Bijuu: Kokuo
Jinchuriki: Han
number of tails: 6
Bijuu: Saiken
Jinchuriki: Utakata
number of tails: 7
Bijuu: Chomei
Jinchuriki: Fu
number of tails: 8
Bijuu: Gyuki
Jinchuriki: Killer Bee
number of tails: 9
Bijuu: Kurama
Jinchuriki: Naruto Uzumaki

Subukan ding i-uncomment yung print() para dun sa result ng split() at i-run uli yung program. Makikita mo kung ano muna yung nangyari bago na-print yung output.

print(data) # uncomment this to see that split() produces a list

Back to Main

Functions

Madalas natin ma-eencounter na meron mga steps within sa program natin that may benefit kung i-bbundle natin sila. Maari nating ipag sama-sama ang mga steps na part ng isang goal at ilagay sila sa isang function. Ang mga common na reason kung bakit ginagawa to ay:

  1. Para i-organize ang code

  2. Para maging reusable ang code

Organize - Importante ang pag-organize para sa ating mga humans. Nakakatulong ito para hindi magulo at mas madaling i-manage ang mga bagay bagay. Kung maglilinis ka ng kwarto mo, maaaring ilagay mo rin ang mga gamit mo sa specific na lagayan base sa silbi nila. Ganito rin pagdating sa code.

Reuse - Malaking bagay din yung magamit natin uli yung same code para sa iba pang part ng program. Kapag nagsusulat ka ng code, ikaw mismo mahahalata mo na may mga steps na paulit-ulit lang. Kapag may ganun, it's a good candidate para ilagay sa isang function.

To create a function ginagamit natin ang def keyword. At kagaya ng mga if statements at mga loops na nadiscuss na natin, indented din ang nakapaloob na code sa isang function.

def my_function():
<common_task>
...

Gumawa ng file at bigyan ito ng filename na countdown-function.py. Pagkatapos ilagay ang code na ito sa file:

import time

# define the function
def countdown_10_sec():
n = 10

while n >= 1:
print(n)
time.sleep(1) # sleep for 1 second
n -= 1

# call the function to use it
countdown_10_sec()

# call the function again
countdown_10_sec()

Yung laman ng function should look familiar kasi ito rin yung countdown example natin. Mainly, ang nagbago lang dito is yung nadagdag na time.sleep(1) at naka-fix sya sa 10 para 10 seconds.

NOTE: Gumamit uli tayo ng import in this example. Noong una ang ginagawa natin is import sys kapag kailangan natin tumanggap ng input. Ngayon naman import time para magamit natin yung sleep() kasi kailangan natin i-pause ang program every 1 second. Again, dadaanan natin ang import in a later topic.

Pagka-run mo ng program ang output nya should ba countdown from 10 to 1 at twice dapat. Mapapansin mo rin na nagppause sya every second gaya ng isang countdown timer.

> python countdown-function.py
10
9
...
2
1
10
9
...
2
1

Back to Main

Function arguments

Sa previous example natin na countdown-function, yung countdown_10_sec na function is specific talaga ang goal nya which is tama lang naman dahil ideally ganun dapat ang functions. However, as you may have noticed, fixed ang result ng function na ito. Lagi lang sya mgccountdown from 10 to 1.

It's very common na gumawa ng function na magiiba ang result or output base sa input. Ibig sabihin, maaari tayong magpasa ng input sa function, at dito magbabase kung ano man yung kalalabasan ng output. For example, ang 2 magkaibang input ay magreresulta sa 2 magkaibang output.

Ang input sa function ay tinatawag na argument. Familiar ka na dito. Kung matatandaan mo nung makailang beses tayo gumamit ng sys.argv para tumanggap ng input yung program natin, halos pareho lang yung gagawin natin ngayon pero argument para sa function, hindi para sa buong program.

Makakapag-define tayo ng function that accepts an argument by specifying it in between the parentheses:

def my_function(my_arg):
<common_task>
...

Pwede ring tumanggap ng multiple arguments.

def my_function(arg1, arg2, arg3):
<common_task>
...

Gumawa ng file at bigyan ito ng filename na countdown-function-arg.py. Pagkatapos ilagay ang code na ito sa file:

import sys
import time

# define the function to accept an argument
def countdown_seconds(n):
while n >= 1: # n is now from argument
print(n)
time.sleep(1)
n -= 1

number_from_user = sys.argv[1]
sec = int(number_from_user)

# call the function with an argument
countdown_seconds(sec)

Ngayon i-run ang program at bigyan ito ng argument na number. For example:

> python countdown-function-arg.py 5
5
4
3
2
1
> python countdown-function-arg.py 10
10
9
...
2
1

Back to Main

Return statement

Nadaanan na natin kung paano gumawa ng function at kung paano ito pwedeng tumanggap ng input through arguments. Pero kung nakakapag-specify na tayo ng input para sa function natin, hindi ba mas maganda kung makapag-specify din tayo ng kanyang output?

Kung ano man ang processing na gawin sa loob ng function, meron itong final result. Usually kailangan natin itong result na ito palabas ng function. Bale ito ang kanyang magiging output.

Pagkatapos gawin ng function ang dapat nyang gawin, we can return a value from the function by using the return statement.

def my_function(my_arg):
<common_task>
...
return my_result

Kung ano ang value na binigay mo sa return, ito ang makukuha mo na value kapag ginamit mo ang function. You can use a variable para ma-capture kung ano man ang value na ibabalik ng function.

function_result = my_function(arg)

Then maaari mong gamitin yung variable na yun for further processing.

Gumawa ng file at bigyan ito ng filename na countdown-function-return.py. Pagkatapos ilagay ang code na ito sa file:

import sys

def countdown(n):
desc_numbers = [] # list to hold the numbers

while n >= 1:
desc_numbers.append(n) # populate list
n -= 1

return desc_numbers # return list when finished

number_from_user = sys.argv[1]
num = int(number_from_user)

# call the function and save result to variable
desc_numbers_list = countdown(num)

print(desc_numbers_list)

Ngayon i-run ang program at bigyan ito ng argument na number. For example:

> python countdown-function-return.py 5
[5, 4, 3, 2, 1]
> python countdown-function-return.py 10
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

Back to Main

Modules

Habang lumalaki yung code natin, magkakaroon at magkakaroon ng mga functions na related sa isa't-isa. Ito yung time kung saan you might consider na i-bundle sila together in a module.

Ang module ay separate file kung saan ang purpose is para i-import ito sa isa pang file. For example, yung pinaka main file ng program mo will import another file (a module) na naglalaman ng mga functions that deal with certain functionality. To import a module, we use the import keyword.

import <name_of_module>

Gumamit tayo noon ng sys module para tumanggap ng input. Gumamit din tayo ng time module para ma-pause yung program natin every second.

import sys

import time

NOTE: Hindi lang necessarily functions ang laman ng isang module. It's still code, pero nasa ibang file lang. Ang module ay maaaring maglaman ng variables (ex. in the sys module we used the argv variable). Ang module ay maaari ding maglaman ng classes which is pag-uusapan natin sa next topic.

Nakailang version din tayo ng countdown sa mga nakaraang topics natin about functions. Ilagay natin sila lahat sa isang module total similar sila sa isa't-isa.

Gumawa ng file at bigyan ito ng filename na countdownfunc.py. Pagkatapos ilagay ang code na ito sa file:

import time

def countdown_10_sec():
n = 10

while n >= 1:
print(n)
time.sleep(1)
n -= 1

def countdown_seconds(n):
while n >= 1:
print(n)
time.sleep(1)
n -= 1

def countdown(n):
desc_numbers = []

while n >= 1:
desc_numbers.append(n)
n -= 1

return desc_numbers

Gumawa ulit ng isa pang file at bigyan ito ng filename na maincountdown.py. Pagkatapos ilagay ang code na ito sa file:

import countdownfunc

# call all module functions using:
# <module_name>.<function_name>(<any_arguments>)

countdownfunc.countdown_10_sec()

countdownfunc.countdown_seconds(5)

desc_nums = countdownfunc.countdown(5)
print(desc_nums)

Ang ginawa natin dito is yung maincountdown.py yung ating main file for our program pagkatapos yung countdownfunc.py naman ay nagsisilbing module na ini-import natin for its "countdown" functionality.

NOTE: Kung mapapansin mo, yung countdown lang yung function kung saan sinave natin yung result nya into a variable. Sa 3 function, sya lang yung hindi nagdidisplay ng output. Instead, nagrereturn lang sya ng value.

Pagka-run mo ng program ganito dapat yung output.

> python maincountdown.py
10
9
...
2
1
5
4
3
2
1
[5, 4, 3, 2, 1]

Back to Main

Objects

Ang objects na marahil ang pinaka-kumplikado na topic ng paguusapan natin. Kaya naman iniwasan kong banggitin ito up until now. Pero ang katotohanan is kanina pa tayo actually gumagamit ng objects. Yun ay dahil lahat ng na-encounter natin sa Python mula pa ng umpisa ng tutorial na ito are all objects (surprise!).

Lahat ng ginamit natin na strings, integers, booleans, etc. ay objects. Lahat ng ginamit natin na lists, tuples at dictionaries are also objects. In fact, even functions and modules are objects.

Kaya nung nag-check tayo ng type ng mga values sa topic ng Types, ang chinecheck talaga natin is yung type ng object.

> python mission-with-types.py
mission: <class 'str'>
team: <class 'int'>
is_success: <class 'bool'>

NOTE: Ang class is yung pinaka template ng object. Lahat ng objects ay may pinagbasehan na class. Sa example natin mamaya, gagawa tayo ng class.

So ano nga ba ang mga objects? Ang object ay ang concept sa object-oriented programming. Ang approach sa object-oriented programming is pagsamahin ang data at functions in one package. Basically, kung meron kang data, meron narin dapat itong kakayahan na magsagawa ng basic processing sa sarili nito.

Here are a few examples of data na ginamit natin that demonstrated yung ganitong behavior.

From mission-ranks example:

# ex. rank_input has a value of a string: 'a'
rank_input.upper() # upper() takes the string from 'a' to 'A'

From tailed-beast example:

# ex. x has a value of a string: 'Kurama,9,Naruto Uzumaki'
x.split(',') # split(',') takes the string from 'Kurama,9,Naruto Uzumaki' to ['Kurama', '9', 'Naruto Uzumaki']

Marahil napaisip ka na kung bakit mukha lang functions ang upper() at split(). Yun ay dahil functions lang naman talaga sila. But in this case, we refer to them as methods. Isipin mo na lang na ang methods are just functions na naka-link sa isang object.

Makikita mo agad yung difference between a normal function and a method:

my_function(my_data) # call a function

my_object.my_method() # call an object's method

Gumawa ng file at bigyan ito ng filename na tailed-beast-object.py. Pagkatapos ilagay ang code na ito sa file:

# using normal data and functions

def extractdetails(beast):
data = beast.split(',')
return data

def displaydetails(data):
print("number of tails:", data[1])
print("Bijuu:", data[0])
print("Jinchuriki:", data[2])

one_tail = 'Shukaku,1,Gaara'

one_tail_details = extractdetails(one_tail)
displaydetails(one_tail_details)

# similar to above, but by combining data and functions into an object

class TailedBeast: # create a class so we can create our own objects
# define methods - methods have self as first argument
def extractdetails(self, beast):
self.data = beast.split(',') # save data to its own variable/s

def displaydetails(self):
print("number of tails:", self.data[1])
print("Bijuu:", self.data[0])
print("Jinchuriki:", self.data[2])

# create an object based on the TailedBeast class
four_tails = TailedBeast() # an instance of TailedBeast

# use its methods
four_tails.extractdetails('Son Goku,4,Roshi')
four_tails.displaydetails()

# access its data
print(four_tails.data) # data specific to four_tails

# we can keep on creating more TailedBeast objects
eight_tails = TailedBeast() # another instance of TailedBeast

eight_tails.extractdetails('Gyuki,8,Killer Bee')
eight_tails.displaydetails()

print(eight_tails.data) # data specific to eight_tails

# both instances show that they are of type 'TailedBeast'
print(type(four_tails))
print(type(eight_tails))

Pagka-run mo ng program ganito dapat yung output.

> python tailed-beast-object.py
number of tails: 1
Bijuu: Shukaku
Jinchuriki: Gaara
number of tails: 4
Bijuu: Son Goku
Jinchuriki: Roshi
['Son Goku', '4', 'Roshi']
number of tails: 8
Bijuu: Gyuki
Jinchuriki: Killer Bee
['Gyuki', '8', 'Killer Bee']
<class '__main__.TailedBeast'>
<class '__main__.TailedBeast'>

NOTE: It's worth noting na lahat ng string, integer, boolean at iba pang objects sa Python ay may pinagbasehan din na class. Built-in lang ang mga class na ito.

Where to go from here?

Sana ay natuto at nag-enjoy ka sa tutorial na ito. Again, for questions and discussions about Python or programming in general, pwede kang sumali sa FB community namin: Programming and I.T. Automation Philippines

Tapos kung nagustuhan mo ang tutorial na ito at gusto mo pa ng tips about Python or Programming in general, consider to like / follow the Zeroslash FB page.

Kung nagustuhan mo ang tutorial na ito at nais mong mas matuto pa about Python at mahasa ang iyong coding skills, you can check out yung aking Programming Fundamentals With Python online course. As the name suggests, it goes more into programming fundamentals gamit ang Python. It also comes with a lot of hands-on coding exercises para sigurading maraming practice.

Linux Command Reference

yum

Is a tool for software package management in Redhat Linux or Linux distributions based on Redhat Linux such as Centos. It allows us to get information about a software package, install it, or delete it.

example usage:

$ sudo yum install <software-package-name>

Installing Vagrant

Back to Main

True division vs Floor division

Category: python, programming

There are 2 different division operators in Python.

The / operator performs true division. This type of division always consider that there could be a remainder. Therefore it always produces floating-point results.

>>> 12 / 5
2.4

>>> 12 / 3
4.0

The // operator performs floor division. This type of division truncates fractional results (the remainder). It will convert them down to their floor value.

>>> 12 // 5
2

>>> 12 // 3
4

Do you see the difference from the true division examples?

The type of the result however depends on the type of its operands.

>>> 12 // 3.0
4.0

NOTE: Floor means the closest whole number below the real result (ex. 2.4 becomes 2). So in reality this is more of "round down" rather than just "truncate".

Due to their nature you might see these types of division through alternative terms.

True division can sometimes be called Floating-point division since it keeps the remainder in its result.

Floor division can sometimes be called Integer division. There are instances that it's even called truncating division. However, as noted above, the result being truncated isn't necessarily the point but rather the result being "round down". Also, floor division may not always result to an integer, which we will discuss further below.

How true division produces its result

We discussed that the / operator returns a float. This is regardless if there's a remainder or none.

From our previous examples, a result with a remainder will be like 2.4 and a result without a remainder will be like 4.0.

It performs true division regardless of the type of its operands. If you noticed, both of our examples for true division have integer operands but their results were still floats.

Converting one of the integer operands to a float wouldn't matter.

>>> 12 / 5.0
2.4

>>> 12 / 3.0
4.0

How floor division produces its result

We discussed that the // operator rounds down to the closest whole number (no remainder) below the real result.

It performs floor division regardless of the type of its operands. However, the type of its operands will have an effect in the result.

It will return an integer if both of its operands are integers.

>>> 12 // 3
4

It will return a float if any of its operands is a float.

>>> 12 // 3.0
4.0

Back to Main

Chained multiple comparisons for range tests

Category: python, programming

Python allows putting together a chain of magnitude comparisons (ex. less than '<' or greater than '>' expressions). This is primarily used for range tests. For example, you can test if a number is within a range of numbers.

An expression like this would look something like:

lowest < N < highest

Here's a breakdown of this expression.

  1. We are comparing if N is bigger than lowest (lowest < N)

  2. We are comparing if N is smaller than highest (N < highest)

As long as N meets both of these conditions, then N falls between lowest and highest. Therefore, N is within range.

NOTE: Since we are using the less than operator (<), of course, the proper way to read no. 1 would be:

We are comparing if lowest is smaller than N (lowest < N)

However, our focus is N and comparing it relative to what's on its left (lowest) and what's on its right (highest). I chose to keep N as the main point of reference.

Let's try out our example.

>>> lowest = 1
>>> highest = 10
>>> N = 7

In this case our range is between 1 to 10. Then the value we are testing is 7. Let's see if 7 is within range.

>>> lowest < N < highest
True

The result is True so 7 is indeed within range.

In our breakdown, there were 2 comparisons. They were exactly what was going on. We just happen to be able to chain them together in the form of lowest < N < highest.

In fact, chained comparisons are just acting like a shorthand.

We could have also written the same range test like this:

>>> lowest < N and N < highest
True

The results are the same, but you can see how the shorthand version earlier seems more clear in saying - N should be between lowest and highest.

Back to Main

Difference between interactive shell's echo and print displays

Category: python, programming

If you notice there's a difference in the output when you just enter the variable name in the Python interactive shell versus when you print it using the print() function.

>>> backyard = 'plant vegetables for food'

Simply echo the variable.

>>> backyard
'plant vegetables for food'

Print the variable.

>>> print(backyard)
plant vegetables for food

In both cases we can see the value of our string, but echoing the variable shows the string with quotes while printing the variable has none. It's a small difference, but the question is why?

It's important to explore this difference because this difference may not be as simple as our string example here. In other objects that we might encounter, it is possible that the difference in display is significant. We want to know when to use one over the other.

This difference in display is caused by 2 built-in functions. Python's built-in functions repr() and str() are responsible for displaying an object.

repr()

When we echo a variable in the interactive shell:

>>> backyard
'plant vegetables for food'

This relies on repr(). This built-in function displays the object in its "code" form. Consider this as a "Python" kind of display.

str()

On the other hand, when we print a variable:

>>> print(backyard)
plant vegetables for food

This relies on str(). This built-in function is intended to display an object in a more user-friendly way.

NOTE: If we inspect an object, it's possible to see these functions being used under the hood. You can use the dir() function on an object and you'll see the methods __repr__ and __str__. Once you see them, you can check what each method does.

Using our example, our string object does have both the __repr__ and __str__ methods and uses the repr() and str() functions respectively.

>>> help(backyard.__repr__)
Help on method-wrapper:

__repr__ = <method-wrapper '__repr__' of str object>
Return repr(self).

>>> help(backyard.__str__)
Help on method-wrapper:

__str__ = <method-wrapper '__str__' of str object>
Return str(self).

A typical case for providing both a repr() display and str() display is to have str() show a simpler version of what the object contains while repr() can provide more details that can be useful for a programmer.

It's also worth mentioning the following situations:

  1. You may encounter an object that implements both __repr__ and __str__ methods (it has both repr() and str()) and both the displays are exactly the same. This means there's no difference when you echo its variable versus when you print its variable.

  2. You may encounter an object that does not implement the __str__ method (it does not use str()). It could just mean that there's no need for a more user-friendly display of an object.

Back to Main

How variables are used

Category: python, programming

Variables are just names that we attach to our data so we can track and maintain them as our program runs.

Most of the variable names that we will use are variables that we create although there are built-in names from Python too.

Since everything in Python is an object (including our data), we can say that we attach variables to an object. Since the variable is associated with an object, the variable is used to reference that object anywhere in the program. This is how we keep track of our data/objects while our program is running.

When using variables, here are the main points to understand.

Create variables as you need them

Variables in Python are not created ahead of time but instead created at the time that they are first assigned values.

status = 'online' # create/assign variables at any point in your program

NOTE: This point is made since there are programming languages where you need to declare a variable ahead of time.

Assign variables before using them

Since variables need to be assigned with a value first before they come into existence, this means they need to be assigned first before using them in expressions.

status = 'online' # assign first
if status == 'online': # then use in expressions
...

Variables gets replaced with their value

When variables are used in expressions, they are replaced with their associated value / object.

status = 'online'
if status == 'online': # status variable is replaced with it's value 'online'
...

Back to Main

Operator overloading

Category: python, programming

In Python, an operation's behavior can change depending on the types of objects that are part of the operation. If a programming language can do this, it means it supports Polymorphism.

This is why we can change the meaning of the + operator based on its operands.

If the operands are numbers such as 5 + 5, then the + operator will perform addition.

>>> 5 + 5
10

If the operands are strings such as 'level: ' + str(5), then the + operator will perform concatenation.

>>> 'level: ' + str(5)
'level: 5'

This is called operator overloading. When an operator is overloaded, it means the operator will behave differently with a different type of object like what we did with our + operator example.

As you can see, an operator can then be used across multiple types of objects. This is all possible because of Polymorphism.

Python will automatically perform this conversion on its built-in types that supports it. But it's worth noting that you can also add the functionality of an existing operator to your own custom objects (ex. yourownobj1 + yourownobj2). You'll be able to use the + operator in your own way.

Back to Main

Automatic type conversion with mixed numeric types

Category: python, programming

Python is able to automatically convert the type of a number in an expression. For example, converting an integer to a float.

It performs this automatic conversion when you are performing an operation between different types. For example, if you're adding an integer and a float such as:

5 + 1.2

With one being an integer and the other being a float, obviously the result should be only either one of them. The question is which one?

What Python does is convert the simpler type of the two to match the more complex one.

In our example, 5 + 1.2, 5 is an integer and 1.2 is a float. Between an integer and a float, the float is more complex and so the integer will be converted up to a float (think of it as being upgraded). What ends up happening is that Python is now performing the operation between the same types - both are now floats.

With that said, the integer 5 becomes the float 5.0 in the background.

>>> 5 + 1.2
6.2

As you can see, Python will handle this conversion on its own and we don't have to do anything.

It's worth noting that, you may decide to specifically convert types. Using our example we can do:

>>> float(5) + 1.2
6.2

But this is usually not required as long as you expect the result to be a float.

Back to Main

Integer syntax

Category: python, programming

Positive and negative integers

An example of an integer is the number 7. This is a positive number (a positive integer).

>>> 7
7

To turn this into a negative number (a negative integer), we just place a negative sign (-) before it like below.

>>> -7
-7

No leading zeros

Leading zeros is not allowed. So if you put a zero before an integer, you will get an error.

>>> 07
File "<stdin>", line 1
07
^
SyntaxError: invalid token

Space between numbers and operators

It's recommended to have a space between numbers and operators such as math / arithmetic operators so that it's easier to read. For example, here's how you would normally do addition.

>>> 9 + 9
18

But it's worth noting that the spaces in between are not required.

>>> 9+9
18

The above example is valid, only that it's not advisable for your real programs since it's less readable. Here's how a bunch of math operations without spaces between them might look like.

>>> 9+9*5-29
25

As you can see, it's not very pleasing to look at and forces you to really inspect it just to make sure you understand it correctly.

Whitespace is important for readability even if it's as simple as adding numbers together. It's even more important for complex calculations.

Back to Main

Types

Category: python, programming

When creating a program, it will consist of different parts. These are the building blocks of a program, mainly data and instructions on how to handle the data.

In an programming language like Python, these different parts are all objects. Data, functions, and even programs themselves (modules) are treated as objects in Python.

Each of these objects has a classification to describe what they are or what their purpose is. We call this classification a type. So when we're able to identify the type of an object, it tells us what the object is.

This is just an example, but let's say we have an object with the type "Keyboard". Knowing this gives us an idea of what this object is about.

Basic Types in Python

Python has a number of built-in types. Here are some examples of basic data types.

  1. Integer - such as 7

  2. Float - such as 1.2

  3. String - such as 'Computer'

  4. Boolean - such as True

If we look at these built-in types, we could already get an idea on what they are used for. For example, Integers and Floats are for numbers.

What can we do with numbers? Of course, one example is we could perform addition on them. Let's say we had the integers 7 and 3, adding the two together gives us the integer 10. It looks like we just did some basic math, but this concept is important in understanding types which we will discuss next.

Why do we have Types?

Here's a simple concept to explain this. If we try to add the integer 7 with the string 'Computer', that doesn't sound right isn't it?

If we tell our program to do this it will know that it doesn't make sense to perform addition between numbers and words, or to be specific, an integer type (7) and a string type ('Computer'). But performing addition between the integer 7 and the integer 3 will work perfectly since they're both of the integer type. Based on this, we can also say that the type of an object sets the rules on how the object can be used.

This is very important because we want to make sure that we humans (the one giving the instructions) and computers (the one executing the instructions) are on the same page. We want to make sure that computers understand our intentions.

Imagine if a computer didn't understand that 7 is an integer, that 'Computer' is a string, and that the two cannot be added together.

How to check an object's Type

To determine the type of an object, we use the type() function. Here's an example for the integer number 7.

>>> type(7)
<class 'int'>

In the output, you can see that it says class 'int' which means class integer. In this discussion, class and type means pretty much the same thing. However, a class is another topic on its own.

Here's another way of interpreting this. The number 7 belongs to the integer class, just as number 3 and the number 10 is. If you were an object, you would belong to the human class.

Back to Main

Literal

Category: python, programming

You might encounter the term 'literal'. When we say 'literal' we are referring to the values that we directly set in our code.

For example we might use the integer number 4, or the string 'intel' itself. Values like 4 and 'intel', when used directly, are what we call literals.

To understand this better, in our expressions we might have an operand that is an actual value, not a variable. We can think of this as the "hard-coded" values in our code.

>>> cores = 4
>>> cores // 2
2

Here we assign the variable cores a value of 4. Then we divide cores with 2.

The value 2 is an integer literal.

Let's look at another example.

>>> cpu = 'intel'
>>> cpu + ' socket'
'intel socket'

Here we assign the variable cpu to a value 'intel'. Then we concatenate intel with ' socket'.

The value 'socket' is a string literal.