Module 2: Fundamentals of Python Programming Language
Module 2: Fundamentals of Python Programming Language
Programming Language
Dates
We often need current date and time when
logging errors and saving data
# To get current date and time
# we need to use the datetime library
from datetime import datetime
current_date = datetime.now()
# the now function returns a datetime object
print('Today is: ' + str(current_date))
Day: 6
Month: 6
Year: 2019
There are functions you can use with datetime
objects to manipulate dates
from datetime import datetime, timedelta
today = datetime.now()
print('Today is: ' + str(today))
Logic errors
Runtime errors
# This code will fail when run
x = 42
y = 0
print(x / y)
Sorry
Use string functions to make case insensitive
comparisons
name = ‘JUNARD'
if name.lower() == ‘junard':
print(‘Hello, Sir Junard')
else:
print(‘Sorry')
TRUE FALSE
FALSE TRUE
If you have a list of possible values to check , you can
use the in operator
if province in(‘Cebu',‘Samar',‘Negros'):
tax = 0.05
elif province == ‘Batangas':
tax = 0.13
else:
tax = 0.15
If an action depends on a combination of
conditions you can nest if statements
if country == ‘Philippines':
if province in(‘Cebu',\
‘Samar',‘Negros'):
tax = 0.05
elif province == ‘Batangas':
tax = 0.13
else:
tax = 0.15
else:
tax = 0.0
Collections
Lists are collections of items
ece_teachers = [‘Susana', ‘Valdezamo‘,’Lotis’,\
‘Rachel’,’Allan’,’Junard’]
scores = []
scores.append(98) # Add new item to the end
scores.append(99)
print(names)
print(scores)
print(scores[1]) # Collections are zero-indexed
['Susan‘, ‘Valdezamo’, ‘Lotis’, ‘Rachel’, ‘Allan’, ‘Junard’]
[98, 99]
99
Arrays are also collections of items
from array import array
scores = array('d')
scores.append(97)
scores.append(98)
print(scores)
print(scores[1])
array('d', [97.0, 98.0])
98.0
What's the difference?
Simple types such as numbers Store anything
Must all be the same type Store any type
Arrays Lists
Common operations
names = ['Susan', ‘Joselito']
print(len(names)) # Get the number of items
names.insert(0, ‘Lotis') # Insert before index
print(names)
names.sort()
print(names)
2
[‘Lotis', 'Susan', ‘Joselito']
[‘Joselito', ‘Lotis', 'Susan']
Retrieving ranges
names = [‘Allan', ‘Rachel', ‘Suniel']
presenters = names[0:2] # Get the first two items
# Starting index and number of items to retrieve
print(names)
print(presenters)
Dictionaries Lists
Loops
Basic while loop
i = 1
while i<5:
print(i,’ ’,end=‘’)
i += 1
1 2 3 4
Looping with a list
names = ['Christopher', 'Susan']
index = 0
while index < len(names):
print(names[index])
index = index + 1
Christopher
Susan
Basic for loop
for i in range(1,5):
print(i,’ ’,sep=‘--’,end=‘’)
1--2--3--4--
Loop through a collection
for name in ['Christopher', 'Susan']:
print(name)
Christopher
Susan
End of Module 2
Thank you