College of Information Technology
First Semester, A.Y. 2024-2025
MODULE 4
CHAPTER 2.2: Getting Wet in Python
Introduction
Python is a high-level programming language for general-purpose programming. It is an open source, interpreted,
objected-oriented programming language. Python was created by a Dutch programmer, Guido van Rossum. The name of
Python programming language was derived from a British sketch comedy series, Monty Python's Flying Circus. The first
version was released on February 20, 1991. The topics are broken down into modules with a numbers of 1 through 13,
where each day contains several topics with easy-to-understand explanations, real-world examples, many hands on
exercises and projects.
Date and Time Allotment
Week 3 (5 hours)
I. Objectives
At the end of the end of this module, students should be able to:
1. Understand Chaining Comparison Operators
2. Learn how to use Chaining Comparison Operators
3. Understand Looping
4. Learn how to use while loop and for loop
II. Lecture
User Input
Interactive input
To get input from the user, use the input function (note: in Python 2.x, the function is called raw_input
instead, although Python 2.x has its own version of input that is completely different):
Python 2.x Version ≥ 2.3
name = raw_input("What is your name? ")
Security Remark Do not use input() in Python2 - the entered text will be evaluated as if it were a Python
expression (equivalent to eval(input()) in Python3), which might easily become a vulnerability. See this
article for further information on the risks of using this function.
Python 3.x Version ≥ 3.0
name = input("What is your name? ")
The remainder of this example will be using Python 3 syntax.
The function takes a string argument, which displays it as a prompt and returns a string. The above code provides a
prompt, waiting for the user to input.
name = input("What is your name? ")
If the user types "Bob" and hits enter, the variable name will be assigned to the string "Bob":
Note that the input is always of type str, which is important if you want the user to enter numbers.
Therefore, you need to convert the str before trying to use it as a number:
x = input("Write a number:")
x / 2
float(x) / 2
NB: It's recommended to use try/except blocks to catch exceptions when dealing with user inputs. For
instance, if your code wants to cast a raw_input into an int, and what the user writes is uncastable, it
raises a ValueError.
Built in Modules and Functions
A module is a file containing Python definitions and statements. Function is a piece of code which execute
some logic.
>>> pow(2,3)
To check the built in function in python we can use dir(). If called without an argument, return the names in
the current scope. Else, return an alphabetized list of names comprising (some of) the attribute of the given
object, and of attributes reachable from it.
> dir( builtins )
To know the functionality of any function, we can use built in function help .
> help(max)
Help on built-in function max in module builtin :
max(...)
max(iterable[, key=func]) -> value
max(a, b, c, ...[, key=func]) -> value
With a single iterable argument, return its largest item.
With two or more arguments, return the largest argument.
Built in modules contains extra functionalities. For example, to get square root of a number we need to include
math module.
> import math
> math.sqrt(16) # 4.0
To know all the functions in a module we can assign the functions list to a variable, and then print the variable.
> import math
> dir(math)
[' doc ', ' name ', ' package ', 'acos', 'acosh',
'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign',
'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1',
'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma',
'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10',
'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh',
'sqrt', 'tan', 'tanh', 'trunc']
it seems doc is useful to provide some documentation in, say, functions
> math. doc
'This module is always available. It provides access to the\nmathematical
functions defined by the C standard.'
In addition to functions, documentation can also be provided in modules. So, if you have a file named
helloWorld.py like this:
"""This is the module docstring."""
def sayHello():
"""This is the function docstring."""
return 'Hello World'
You can access its docstrings like this:
> import helloWorld
> helloWorld. doc
'This is the module docstring.'
> helloWorld.sayHello. doc 'This
is the function docstring.'
For any user defined type, its attributes, its class's attributes, and recursively the attributes of its class's base
classes can be retrieved using dir()
> class MyClassObject(object):
... pass
...
> dir(MyClassObject)
[' class ', ' delattr ', ' dict ', ' doc ', ' format ', ' getattribute ', ' hash ',
' init ', ' module ', ' new ', ' reduce ', ' reduce_ex ', ' repr ', ' setattr ',
' sizeof ', ' str ', ' subclasshook ', ' weakref ']
Any data type can be simply converted to string using a builtin function called str. This function is called by
default when a data type is passed to print
> str(123)
Installation of Python 2.7.x and 3.x No need to elaborate here!
Chapter 2: Python Data Types
Data types are nothing but variables you use to reserve some space in memory. Python variables do not
need an explicit declaration to reserve memory space. The declaration happens automatically when you
assign a value to a variable.
String Data Type
String are identified as a contiguous set of characters represented in the quotation marks. Python allows for
either pairs of single or double quotes. Strings are immutable sequence data type, i.e each time one makes any
changes to a string, completely new string object is created.
a_str = 'Hello World'
Set Data Types
Sets are unordered collections of unique objects, there are two types of set:
1. Sets - They are mutable and new elements can be added once sets are defined
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
> {'orange', 'banana', 'pear',
'apple'} a = set('abracadabra')
> {'a', 'r', 'b', 'c', 'd'}
a.add('z')
print(a)
> {'a', 'c', 'r', 'b', 'z', 'd'}
2. Frozen Sets - They are immutable and new elements cannot added after its defined.
b = frozenset('asdfagsa')
print(b)
> frozenset({'f', 'g', 'd', 'a', 's'})
cities = frozenset(["Frankfurt", "Basel","Freiburg"])
print(cities)
> frozenset({'Frankfurt', 'Basel', 'Freiburg'})
Numbers data type
Numbers have four types in Python. Int, float, complex, and long.
int_num = 10
List Data Type
A list contains items separated by commas and enclosed within square brackets [].lists are almost similar to
arrays in C. One difference is that all the items belonging to a list can be of different data type.
list = [123,'abcd',10.2,'d']
list1 = ['hello','world']
Dictionary Data Type
Dictionary consists of key-value pairs. It is enclosed by curly braces {} and values can be assigned and
accessed using square brackets[].
dic={'name':'red','age':10}
print(dic)
Tuple Data Type
Lists are enclosed in brackets [ ] and their elements and size can be changed, while tuples are enclosed in
parentheses ( ) and cannot be updated. Tuples are immutable.
tuple = (123,'hello')
tuple1 = ('world')
print(tuple + tuple1)
Comments and Documentation
Single line, inline and multiline comments
Comments are used to explain code when the basic code itself isn't clear.
Python ignores comments, and so will not execute code in there, or raise syntax errors for plain English
sentences. Single-line comments begin with the hash character (#) and are terminated by the end of line.
Single line comment:
Inline comment:
Comments spanning multiple lines have """ or ''' on either end. This is the same as a multiline string,
but they can be used as comments:
"""
This type of comment spans multiple lines.
These are mostly used for documentation of functions, classes and
modules. """
Date and Time
Parsing a string into a timezone aware datetime object
Python 3.2+ has support for %z format when parsing a string into a datetime
object.
UTC offset in the form +HHMM or -HHMM (empty string if the object is naive).
Python 3.x Version ≥ 3.2
import datetime
dt = datetime.datetime.strptime("2016-04-15T08:27:18-0500", "%Y-%m-%dT%H:%M:%S%z")
Computing time differences
the timedelta module comes in handy to compute differences between times:
from datetime import datetime, timedelta
now = datetime.now()
then = datetime(2016, 5, 23)
Specifying time is optional when creating a new datetime object
delta = now-then
delta is of type timedelta
print(delta.days)
print(delta.seconds)
To get n day's after and n day's before date we could use:
n day's after date:
def get_n_days_after_date(date_format="%d %B %Y", add_days=120):
date_n_days_after = datetime.datetime.now() + timedelta(days=add_days)
n day's before date:
def get_n_days_before_date(self, date_format="%d %B %Y", days_before=120):
date_n_days_ago = datetime.datetime.now() - timedelta(days=days_before)
Basic datetime objects usage
import datetime
today = datetime.date.today()
now = datetime.datetime.now()
The datetime module contains three primary types of objects - date, time, and datetime.
Arithmetic operations for these objects are only supported within same datatype and performing simple
arithmetic with instances of different types will result in a TypeError.
noon-today
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'datetime.time' and
'datetime.date' However, it is straightforward to convert between types.
print('Time since the millenium at midnight: ',
datetime.datetime(today.year, today.month, today.day) - millenium_turn)
print('Time since the millenium at noon: ',
datetime.datetime.combine(today, noon) - millenium_turn)
Simple date arithmetic
Dates don't exist in isolation. It is common that you will need to find the amount of
time between dates or determine what the date will be tomorrow. This can be
accomplished using timedelta objects
import datetime
today = datetime.date.today()
print('Today:', today)
yesterday = today - datetime.timedelta(days=1)
print('Yesterday:', yesterday)
tomorrow = today + datetime.timedelta(days=1)
print('Tomorrow:', tomorrow)
print('Time between tomorrow and yesterday:', tomorrow - yesterday)
This will produce results similar to:
Today: 2016-04-15
Yesterday: 2016-04-14
Tomorrow: 2016-04-16
Difference between tomorrow and yesterday: 2 days, 0:00:00
III. Application/Activity
IV. Assessment
V. Other References
● Introduction to Python® Programming and Developing GUI Applications with PyQT, B.M. Harwani
● https://code.visualstudio.com/docs
● https://devguide.python.org/
● https://www.w3schools.com/python/default.asp
Prepared by:
MHARK ANTHONY ESQUEJO
Faculty, CIT
Checked by:
FREDERICK J. SORIANO, MIT
Program Head, CIT