Module 4 midterm
Module 4 midterm
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.
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):
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
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.
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.
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.
To know the functionality of any function, we can use built in function help .
> help(max)
Built in modules contains extra functionalities. For example, to get square root of a number we need to include
math module.
To know all the functions in a module we can assign the functions list to a variable, and then print the variable.
> dir(math)
[' doc ', ' name ', ' package ', 'acos', 'acosh',
In addition to functions, documentation can also be provided in modules. So, if you have a file named
helloWorld.py like this:
def sayHello():
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()
... 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)
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 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.
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'}
print(a)
2. Frozen Sets - They are immutable and new elements cannot added after its defined.
b = frozenset('asdfagsa')
print(b)
print(cities)
Numbers have four types in Python. Int, float, complex, and long.
int_num = 10
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 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)
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 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.
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:
"""
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).
dt = datetime.datetime.strptime("2016-04-15T08:27:18-0500", "%Y-%m-%dT%H:%M:%S%z")
delta = now-then
print(delta.days)
print(delta.seconds)
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
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)
Today: 2016-04-15
Yesterday: 2016-04-14
Tomorrow: 2016-04-16
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:
Checked by: