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

Module 2: Fundamentals of Python Programming Language

This document provides an overview of key Python concepts covered in Module 2 on fundamentals, including: - Working with dates and times using the datetime library - Conditional logic using if/else statements and comparison operators to check multiple conditions - Error handling using try/except blocks to catch runtime errors - Collections like lists, tuples, dictionaries for storing and retrieving data - Common operations on collections like sorting, inserting, retrieving ranges - Iterating over collections using for and while loops

Uploaded by

April Serundo
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

Module 2: Fundamentals of Python Programming Language

This document provides an overview of key Python concepts covered in Module 2 on fundamentals, including: - Working with dates and times using the datetime library - Conditional logic using if/else statements and comparison operators to check multiple conditions - Error handling using try/except blocks to catch runtime errors - Collections like lists, tuples, dictionaries for storing and retrieving data - Common operations on collections like sorting, inserting, retrieving ranges - Iterating over collections using for and while loops

Uploaded by

April Serundo
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 42

Module 2: Fundamentals of Python

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))

Today is: 2019-06-06 16:17:18.694511


Use date functions to control date formatting
from datetime import datetime
current_date = datetime.now()

print('Day: ' + str(current_date.day))


print('Month: ' + str(current_date.month))
print('Year: ' + str(current_date.year))

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))

# timedelta is used to define a period of time


one_day = timedelta(days=1)
yesterday = today - one_day
print('Yesterday was: ' + str(yesterday))

Today is: 2019-06-06 16:14:24.615495


Yesterday was: 2019-06-05 16:14:24.615495
Error Handling
Syntax errors

Error types Runtime


  errors

Logic errors
Runtime errors
# This code will fail when run
x = 42
y = 0
print(x / y)

Traceback (most recent call last):


File "runtime.py", line 3, in <module>
print(x / y)
ZeroDivisionError: division by zero
Catching runtime errors
try:
print(x / y)
except ZeroDivisionError as e:
# Optionally, log e somewhere
print('Sorry, something went wrong')
except:
print('Something really went wrong')
finally:
print('This always runs on success or failure')

Sorry, something went wrong


Conditions
Your code needs the ability to take different
actions based on different conditions
if price >= 1.00: Symbol Operation
> Greater than
tax = .07
< Less than
print(tax) >= Greater than or equal to
<= Less than or equal to
== is equal to
!= is not equal to
You can add a default action using else
if price >= 1.00:
tax = .07
print(tax)
else:
tax = 0
print(tax)
How you indent your code changes execution
if price >= 1.00: if price >= 1.00:
tax = .07 tax = .07
print(tax) else:
else: tax = 0
tax = 0 print(tax)
print(tax)
Be careful when comparing strings
name = ‘JUNARD'
String
if name == ‘junard': comparisons are
    print(‘Hi, Sir Junard') case sensitive
else:
    print(‘Sorry')

Sorry
Use string functions to make case insensitive
comparisons
name = ‘JUNARD'
if name.lower() == ‘junard':
    print(‘Hello, Sir Junard')
else:
    print(‘Sorry')

Hello, Sir Junard


Multiple Conditions
You may need to check multiple conditions to
determine the correct action
if province == ‘Cebu':
name = ‘bisdak’
if province == ‘Samar':
name = ‘waray’
if province == ‘Batangas':
name = ‘tagalog’
If only one of the conditions will ever occur you
can use a single if statement with elif
if province == ‘Cebu':
tax = 0.05
elif province == ‘Samar':
tax = 0.05
elif province == ‘Batangas':
tax = 0.13
When you use elif instead of multiple if
statements you can add a default action
if province == ‘Cebu':
tax = 0.05
elif province == ‘Samar':
tax = 0.05
elif province == ‘Batangas':
tax = 0.13
else:
tax = 0.15
If multiple conditions cause the same action they
can be combined into a single condition
if province == ‘Cebu' or province == ‘Samar':
tax = 0.05
elif province == ‘Batangas':
tax = 0.13
else:
tax = 0.15
How or statements are processed

First Condition Second Condition Condition evaluates as


TRUE TRUE TRUE
TRUE FALSE TRUE
FALSE TRUE TRUE
FALSE FALSE FALSE
How and statements are processed

First Condition Second Condition Condition evaluates as


TRUE TRUE TRUE
TRUE FALSE FALSE
FALSE TRUE FALSE
FALSE FALSE FALSE
How not statements are processed
First Condition Condition evaluates as

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)

[‘Allan', ‘Rachel', ‘Suniel']


[‘Allan', ‘Rachel']
Another example of list operations
Tuples
- Tuples are like read-only list
- Once we define a tuples, we cannot add or remove items or change the existing items

coordinates = (1,2,3) # defining a tuple

# unpacking a tuple into separate variables


x,y,z = coordinates
print(‘Coordinates: ’,x,y,z)
Coordinates: 1 2 3
Dictionaries
person = {'first': ‘Susan'}
person['last'] = ‘Junard'
print(person)
print(person['first'])

{'first': ‘Susana', 'last': ‘Junard'}


Susan
Dictionaries
me = {‘name’:’Junard Kaquilala’,’age’:30,
‘status’:’single’}
print(me)
me[‘name’] = ‘Sir Kaqs’
print(me[name])

{'name': 'Junard Kaquilala', 'age': 30, 'status': 'single'}


Sir Kaqs
What's the difference?
Key/Value pairs Zero-based index
Storage order not guaranteed Storage order guaranteed

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

You might also like