HO CHI MINH CITY UNIVERSITY OF TRANSPORT
FACULTY OF INFORMATION TECHNOLOGY
SOFTWARE ENGINEERING DEPARTMENT
CHAPTER 6
BUILT-IN FUNCTIONS
AND MODULES
1
CONTENTS
1. Functions
2. Getting Help
3. Input/Output
4. Math Functions
5. Some commonly used functions
6. Working with External Libraries
2
Writing a Simple Program
• Problem: Calculating the area of a circle.
• Algorithm:
1. Get the circle’s radius from the user.
2. Compute the area by applying the following formula:
area = radius * radius * PI
3. Display the result.
• Important issues:
• How to read the radius from console?
• How to use pi in library?
• How to display result to console?
3
1. Functions
• A function is a group of statements that performs a specific task.
• Functions take arguments and return a result.
• Any programming language provides a library of functions that
perform common operations.
• One of the best things about Python is the vast number of high-
quality custom libraries that have been written for it.
• Some of these libraries are in the "standard library“. Others
libraries can be easily added.
• Some built-in functions are always available in the Python
interpreter. → Don’t have to import any modules to use these
functions
4
Built-in Functions
5
2. Getting Help
• The help() function is possibly the most important Python
function
• When you're looking up a function, remember to pass in the name
of the function itself
6
3. Input/Output
Function Description
print( ) Prints to a text stream or the console
input( ) Reads input from the console
format( ) Converts a value to a formatted
representation
open() Opens a file and returns a file object
7
Print to a text stream or the console
• The print() function prints the specified message to:
• Console (Screen)
• A text stream (file)
• Syntax:
print(objects,..., sep=' ', end='\n', file=[Link], flush=False)
• Prints the objects to a stream, or to [Link] by default.
• Optional arguments:
• sep: string inserted between values, default a space
• file: a stream file, defaults to the current [Link] (screen).
• end: string appended after the last value, default a newline (\n).
• flush: specifying if the output is flushed (True) or buffered (False).
Default is False
8
Print to a text stream or the console
9
Print to a text stream or the console
10
Print to a text stream or the console
At this time, there's nothing in the file. Print the contents of the
file are stored in memory until the file is closed.
At this time, contents have been written to the file.
11
Formatting Strings
• Python supports multiple ways to format text strings
1. “Old Style” String Formatting (Modulo Operator)
2. “New Style” String Formatting ([Link]() )
3. f-Strings (Python 3.6+)
12
Formatting Strings
1. Using string modulo operator(%)
• Syntax
<format_string> % (values)
• <format_string>: a string containing one or more conversion
specifiers
• values: inserted into format_string in place of the conversion
specifiers
13
Formatting Strings
• Note:
• String modulo operation isn’t only for printing
• We can also format values and assign them to another
string variable
14
Formatting Strings
Conversion Specifiers
• Conversion specifiers appear in the <format_string> and
determine how values are formatted when they’re inserted.
• Syntax:
%[<flags>][<width>][.<precision>]<type>
• % and <type> are required
• <flags>, <width>, <precision>: optional
15
Formatting Strings
Conversion Type
type Conversion Type Example
d, i, u Decimal integer
x, X Hexadecimal integer
o Octal integer
f, F Floating point
e, E Exponential
c Single character
s, r, a String
16
Formatting Strings
Width and Precision Specifiers
• <width>: specifies the minimum width of the output field.
• <precision>: affects the floating point, exponential, and string
conversion types
17
Formatting Strings
Conversion Flags
• Allow finer control over the display of certain conversion types
Character Controls
# Display of base or decimal point for integer and
floating point values
0 Padding of values that are shorter than the specified
field width
- Value to be left-justified
+ Display of leading sign for numeric values
18
Formatting Strings
Conversion Flags
19
Formatting Strings
2. Using [Link]() method
• Converts a value to a formatted representation
• Syntax
<format_string>.format(arguments)
• <format_string>: a string contain “replacement fields”
surrounded by curly braces “{}”
• Note: If you need to print a brace character, it can be escaped
by doubling: "{{" and "}}".
• arguments: inserted into format_string in place of the
replacement fields
20
Formatting Strings
Replacement fields.
• Syntax:
{ [field_name] [! conversion] [: format_spec] }
• field_name
• Specifies the object whose value is to be formatted.
• May be number or keyword
• Number: position of argument in format() function (0,1,2,…)
• Keyword: name of argument in format() function
• Conversion
• Force a type to be formatted as a string
• Three conversion flags: !s, !r, !a
21
Formatting Strings
22
Formatting Strings
Format Specification
• Syntax:
[[fill]align][sign][#][0][width][grouping_option][.precision][type]
Fill <any character>
Align <, >, ^: Left aligns, Right aligns, Center aligns
= : Places the sign to the left most position
Sign +, - : Use for positive or negative numbers
Space: Use a leading space for positive numbers
# Alternate form for different types
Width A decimal integer defining the minimum field width
Grouping_option , _: Use for a thousands separator
Precision for a floating point value and string
Type d, b, o, x/X: integer in base 10, 2, 8, 16
f/F, e/E, c, s: float, exponent, character, string
23
Formatting Strings
24
Formatting Strings
3. Using f-Strings
• Provide a way to embed expressions inside string literals.
• f-strings are string literals that are prefixed by the letter 'f' or
'F'
• Syntax
f ‘<format_string>’
{ Expression [! conversion] [: format_spec] }
• <format_string>: a string contain expressions inside braces
“{}”
• Expressions: evaluated at run time, not a constant value.
• Following each expression, an optional type conversion or
format specifier may be specified.
• F-strings use the same format specifier as [Link]()
25
Formatting Strings
26
Formatting Strings
27
Formatting DateTime
Directive Meaning Example
%a Weekday as locale’s abbreviated name. Sun, Mon, …, Sat
Sunday, Monday, …,
%A Weekday as locale’s full name.
Saturday
Weekday as a decimal number, where 0 is
%w 0, 1, …, 6
Sunday and 6 is Saturday.
Day of the month as a zero-padded
%d 01, 02, …, 31
decimal number.
%b Month as locale’s abbreviated name. Jan, Feb, …, Dec
January, February, …,
%B Month as locale’s full name.
December
%m Month as a zero-padded decimal number. 01, 02, …, 12
Year without century as a zero-padded
%y 00, 01, …, 99
decimal number.
%Y Year with century as a decimal number. 1970, 1988, 2001
28
Formatting DateTime
Directive Meaning Example
Hour (24-hour clock) as a zero-padded
%H 00, 01, …, 23
decimal number.
Hour (12-hour clock) as a zero-padded
%I 01, 02, …, 12
decimal number.
%p Locale’s equivalent of either AM or PM. AM, PM
%M Minute as a zero-padded decimal number. 00, 01, …, 59
%S Second as a zero-padded decimal number. 00, 01, …, 59
Locale’s appropriate date and time
%c Tue Aug 16 21:30:00 1988
representation.
08/16/88 (None);
%x Locale’s appropriate date representation.
08/16/1988 (en_US);
Day of the year as a zero-padded decimal
%j 001, 002, …, 366
number.
29
Reading Input from the Console
• Reading input enables the program to accept input from the user.
• From Console (Keyboard)
• From File
• Use input( ) function to read input from the Console.
input([<prompt>])
• <prompt>: optional if it is present, it displays message to standard
output without a trailing newline before the input.
• Read input as a string → need to convert the string to the
appropriate type with the functions: int(), float(), complex(),… or
eval()
30
Reading Input from the Console
31
Reading Input from the Console
• Example: Ask the user to input a value for the radius
32
Reading Input from the Console
Reading many values :
Reading list of numbers:
33
4. Math Functions
Function Description
abs() Returns absolute value of a number
divmod() Returns quotient and remainder of integer division
max() Returns the largest of the given arguments or items in
an iterable
min() Returns the smallest of the given arguments or items
in an iterable
pow() Raises a number to a power
round() Rounds a floating-point value
sum() Sums the items of an iterable
34
Math Functions
abs() Funtion divmod() Funtion
• Return the absolute value of a • Return a pair of numbers
number consisting of their quotient and
remainder
• Syntax: abs(x) • Syntax:
• x: required, may be an int or a divmod(divident, divisor)
float number. If the argument is a • Divident and divisor: required,
complex number, its magnitude is may be an integer or a floating
returned. point number.
35
Math Functions
min() Funtion max() Funtion
• Returns the smallest item in an • Returns the largest item in an
iterable iterable
• Syntax:
• Syntax:
max(n1, n2, n3, ...)
min(n1, n2, n3, ...)
max(iterable)
min(iterable)
36
Math Functions
pow() Funtion
• Return x to the power y, modulo z;
• Syntax:
pow(x, y[, z])
• If z is present, x and y must be of integer types, and y must be non-
negative.
37
Math Functions
round() Funtion sum() Funtion
• Return number rounded to ndigits • Sums start and the items of
precision after the decimal point. an iterable from left to right and
returns the total.
• Syntax:
• start defaults to 0.
round(number[, ndigits]) • Syntax:
• If ndigits is omitted or is None, it sum(iterable[, start])
returns the nearest integer to its
input
38
Type Conversion
Function Description
ascii() Returns a string containing a printable representation of an object
bin() Converts an integer to a binary string
bool() Converts an argument to a Boolean value
chr() Returns string representation of character given by integer argument
complex() Returns a complex number constructed from arguments
float() Returns a floating-point object constructed from a number or string
hex() Converts an integer to a hexadecimal string
int() Returns an integer object constructed from a number or string
oct() Converts an integer to an octal string
ord() Returns integer representation of a character
repr() Returns a string containing a printable representation of an object
str() Returns a string version of an object
type() Returns the type of an object or creates a new type object
39
5. Some commonly used functions
Function Description
eval() Evaluates a Python expression
len() Returns the length of an object
range() Generates a range of integer values
dir() Returns a list of names in current local scope or
a list of object attributes
id() Returns the identity of an object
40
Some commonly used functions
eval() Funtion
• Syntax:
eval(expression[, globals[, locals]])
• Expression: a string, is parsed and evaluated as a Python expression
• Globals(Optional): is a dictionary to specify the available global
methods and variables.
• Locals (Optional): is a dictionary to specify the available local methods
and variables
• Using globals and locals to make our eval function safe from any
possible hacks.
41
Some commonly used functions
eval() Funtion
If you pass an empty dictionary as globals, only the built-in functions are
available to expression
42
Some commonly used functions
eval() Funtion
Expression can use sqrt() methods and pi
along with built-in functions
43
Some commonly used functions
len() Funtion
• Returns the number of items in an object.
• Syntax:
len(object)
• Object: may be a sequence (such as a string, bytes, tuple, list, or range)
or a collection (such as a dictionary, set, or frozen set).
44
Some commonly used functions
range() Funtion
• Returns a sequence of integers from start to stop by step.
• Syntax:
range([start,] stop[, step])
• start: Optional. An integer number specifying at which position to start.
Default is 0.
• stop: Required. An integer number specifying at which position to end.
• step: Optional. An integer number specifying the incrementation.
Default is 1.
• Example:
range(n) produces 0,1,2,…,n-1
range(i, j) produces i, i+1, i+2, ..., j-1
45
Some commonly used functions
range() Funtion
46
Some commonly used functions
dir() Funtion
• Returns all properties and methods of the specified object.
• Syntax:
dir([object])
• If object is omitted, return the list of names in the current local scope.
47
Some commonly used functions
dir() Funtion
48
Some commonly used functions
id() Funtion
• Return the “identity” of an object. All objects in Python has its own
unique id.
• This is the address of the object in memory and will be different for
each time you run the program
• Syntax: id(object)
• Object: Any object such as String, Number, List, Class,....
49
6. Working with External Libraries
• A module is a file containing variables and functions intended for
use in other Python programs.
• Module contents are made available to the caller with the import
statement
• There are many Python modules that come with Python as part of
the standard library:
• math
• datetime, time
• random
• string
• …
50
Working with External Libraries
• The import statement:
import <module_name>
• To access variables and functions in the module, need to
use <module_name> and dot notation.
• Import many modules in single statement:
import <module_name>[, <module_name> ...]
51
Working with External Libraries
• If we know we'll be using functions in module frequently we can
import it under a shorter alias:
import <module_name> as <alias>
• Directly access to objects and functions without any dotted prefix:
from <module_name> import *
→ import everything from a module
52
Working with External Libraries
• Import * isn’t necessarily recommended in large-scale production
code. It’s a bit dangerous.
• The problem in this case is that the math and numpy modules both have
functions called log, but they have different semantics.
→ log function in numpy overwrites the log function in math
53
Working with External Libraries
• Import only the specific things we'll need from each module:
from <module_name> import <name(s)>
54