Chapter No 7 : Mathematical Functions, Strings and Objects
C E – 119
Computing Fundamentals (CF)
Compiled By:
Sir Syed University of Engineering & Technology
Engr. Syed Atir Iftikhar
Computer Engineering Department satir@ssuet.edu.pk
University Road, Karachi-75300, PAKISTAN 1
CE - 119 : Computing Fundamentals (CF)
Course Objectives:
This course covers the concepts and fundamentals
of computing and programming. Topics includes
history, components of computers, hardware,
software, operating systems, database, networks,
number systems and logic gates. Also it includes
programming topics such as basic building blocks,
loop, decision making statements.
2
CE - 119 : Computing Fundamentals (CF)
Course Learning Outcomes ( CLO )
CLO Level
Outcome Statement
No. *
Explain the fundamental knowledge and concepts about
1 computing infrastructure including hardware, software, C2
database and networks.
Applying and Implementing number systems and logic
2 C3
gates.
Applying and Implementing problem solving skills and
3 solve problems incorporating the concept of C3
programming. 3
Books
Text Books
1. Computing Essentials, Timothy O’Leary and Linda O’Leary
2. Introduction to Computers, Peter Norton, 6th Edition, McGraw-Hill
3. Introduction to Programming using Python, Daniel Liang
Reference Books:
1. Discovering Computers, Misty Vermaat and Susan Sebok,
Cengage Learning
2. Using Information Technology: A Practical Introduction to Computers
& Communications, Williams Sawyer, 9th Edition, McGraw-Hill
3. Introduction to Python, Paul Deitel, Harvey Deitel
4
Marks Distribution
Total Marks ( Theory ) ___________ 100
Mid Term ___________ 30
Assignments + Quizzes + Presentation ___________ 20
Semester Final Examination Paper ___________ 50
Total Marks ( Laboratory ) ___________ 50
Lab File ___________ 15
Subject Project ___________ 15
Lab Exam/Quiz ( Theory Teacher ) ___________ 20
https://sites.google.com/view/muzammil2050
5
Course Instructors
Muzammil Ahmad Khan muzammil.ssuet@yahoo.com
Assistant Professor, CED
Room No: BS-04
Atir Iftikhar satir@ssuet.edu.pk
Lecturer, CED
Room No: BT-05
6
CE – 119: Computing Fundamentals Chapter
Mathematical Functions,
Strings, and Objects
Compiled By:
Engr. Syed Atir Iftikhar satir@ssuet.edu.pk
7
Motivations
Suppose you need to estimate the area enclosed by
four cities, given the GPS locations
(latitude and longitude) of these cities, as shown in
the following diagram.
How would you write a program to solve this
problem?
8
Objectives
To solve mathematics problems by using the functions in the
math module
To represent and process strings and characters
To encode characters using ASCII and Unicode
To use the ord to obtain a numerical code for a character and
chr to convert a numerical code to a character
To represent special characters using the escape sequence
To invoke the print function with the end argument
To convert numbers to a string using the str function
To use the + operator to concatenate strings
To read strings from the console
To introduce objects and methods
To format numbers and strings using the format function
To draw various shapes and to draw graphics with colors and
9
fonts.
Common Python Built-in Functions
Python provides many useful functions for common
programming tasks.
A function is a group of statements that performs a
specific task.
Python, as well as other programming languages,
provides a library of functions.
You have already used the functions
eval, input, print, and int.
10
Built-in Functions and math Module
>>> max(2, 3, 4) # Returns a maximum number
4
>>> min(2, 3, 4) # Returns a minimu number
2
>>> round(3.51) # Rounds to its nearest integer
4
>>> round(3.4) # Rounds to its nearest integer
3
>>> abs(-3) # Returns the absolute value
3
>>> pow(2, 3) # Same as 2 ** 3
8
11
Common Python Built-in Functions
12
Python Built-in Mathematical Functions
13
Program 3.1 use_the_math_functions.py
import math # import math module to use the math functions
# Test algebraic functions
print("exp(1.0) =", math.exp(1.0))
print("log(2.78) =", math.log(2.78))
print("log10(10, 10) =", math.log(10, 10) )
print("sqrt(4.0) =", math.sqrt(4.0))
# Test trigonometric functions
print("sin(PI/2) =", math.sin(math.pi/2))
print("cos(PI/2) =", math.cos(math.pi/2))
print("degrees(1.57) =", math.degrees(1.57))
print("radians(90) =", math.radians(90))
14
Program 3.1 use_the_math_functions.py
Output:
exp(1.0) = 2.718281828459045
log(2.78) = 1.0224509277025455
log10(10, 10) = 1.0
sqrt(4.0) = 2.0
sin(PI/2) = 1.0
cos(PI/2) = 6.123233995736766e-17
degrees(1.57) = 89.95437383553924
radians(90) = 1.5707963267948966
15
Problem: Compute Angles
Given three points of a triangle, you can compute the
angles using the following formula:
x2, y2
A = acos((a * a - b * b - c * c) / (-2 * b * c))
a B = acos((b * b - a * a - c * c) / (-2 * a * c))
B
c C = acos((c * c - b * b - a * a) / (-2 * a * b))
C
A x3, y3
b
x1, y1
16
Program 3.2 Compute Angles.py
import math
x1, y1, x2, y2, x3, y3 = eval(input("Enter three points: "))
a = math.sqrt((x2 - x3) * (x2 - x3) + (y2 - y3) * (y2 - y3))
b = math.sqrt((x1 - x3) * (x1 - x3) + (y1 - y3) * (y1 - y3))
c = math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2))
A = math.degrees(math.acos((a * a - b * b - c * c) / (-2 * b * c)))
B = math.degrees(math.acos((b * b - a * a - c * c) / (-2 * a * c)))
C = math.degrees(math.acos((c * c - b * b - a * a) / (-2 * a * b)))
print("The three angles are ", round(A * 100) / 100.0,
round(B * 100) / 100.0, round(C * 100) / 100.0)
17
Program 3.2 Compute Angles.py
Output:
Enter three points: 1, 1, 6.5, 1, 6.5, 2.5
The three angles are 15.26 90.0 74.74
The program prompts the user to enter three points
(line 3). This prompting message is not clear.
You should give the user explicit instructions on how to
enter these points as follows:
input("Enter six coordinates of three points
separated by commas\ like x1, y1, x2, y2, x3, y3: "
18
Strings and Characters
A string is a sequence of characters.
String literals can be enclosed in matching
single quotes (') or double quotes (").
Python does not have a data type for characters.
A single-character string represents a character.
letter = 'A’ # Same as letter = "A"
numChar = '4’ # Same as numChar = "4"
message = "Good morning" # Same as message = 'Good morning'
19
NOTE
For consistency, this book uses double quotes for a
string with more than one character and single
quotes for a string with a single character or an
empty string.
This convention is consistent with other
programming languages. So, it will be easy to
convert a Python program to a program written in
other languages.
A string is a sequence of characters.
Python treats characters and strings the same way
20
Unicode and ASCII Code
Python characters use Unicode, a 16-bit encoding
scheme Python supports Unicode.
Unicode is an encoding scheme for representing
international characters.
ASCII (American Standard Code for
Information Interchange) is a small subset of
Unicode.
21
Unicode and ASCII Code
Computers use binary numbers internally. A character is
stored in a computer as a sequence of 0s and 1s.
Mapping a character to its binary representation is called
character encoding. There are different ways to encode a
character. The manner in which characters are encoded is
defined by an encoding scheme.
One popular standard is ASCII (American Standard
Code for Information Interchange), a 7-bit encoding
scheme for representing all uppercase and lowercase
letters, digits, punctuation marks, and control characters.
ASCII uses numbers 0 through 127 to represent characters.
22
Appendix B: ASCII Character Set
ASCII Character Set is a subset of the Unicode from
\u0000 to \u007f
23
ASCII Character Set, cont.
ASCII Character Set is a subset of the Unicode from
\u0000 to \u007f
24
Display of UniCode
A Unicode starts with \u, followed by four hexadecimal
digits that run from \u0000 to \uFFFF.
For example, the word “welcome” is translated into
Chinese using two characters. The Unicode
representations of these two characters are
\u6B22 \u8FCE.
25
Functions ord and chr
>>> ch = 'a'
>>> ord(ch)
>>> 97
>>> chr(98)
>>> 'b'
Python ord() function takes Python chr() function takes
string argument of a single integer argument and return
Unicode character and the string representing a
return its integer Unicode character at that code point.
code point value. 26
Functions ord and chr
The ASCII code for a is 97, which is greater than
the code for A (65).
The ASCII code for lowercase letters are
consecutive integers starting from the code for a,
then for b, c, and so on, up to the letter z.
The same is true for the uppercase letters.
The difference between the ASCII code of any
lowercase letter and its corresponding uppercase
letter is the same: 32.
This is a useful property for processing characters.
27
Escape Sequences for Special Characters
Description Escape Sequence Unicode
Backspace \b \u0008
Tab \t \u0009
Linefeed \n \u000A
Carriage return \r \u000D
Backslash \\ \u005C
Single Quote \' \u0027
Double Quote \" \u0022
28
Printing without the Newline
print(item, end = 'anyendingstring')
print("AAA", end = ' ')
print("BBB", end = '')
print("CCC", end = '***')
print("DDD", end = '***')
• You can use the optional named argument end to explicitly mention the string that
should be appended at the end of the line.
• Whatever you provide as the end argument is going to be the terminating string.
• So if you provide an empty string, then no newline characters, and no spaces will
be appended to your input.
# use the named argument "end" to explicitly specify the end of line string
print("Hello World!", end = ‘’)
print("My name is Selim")
# output:
# Hello World!My name is Selim
29
Escape Sequences for Special Characters
print(item, end = "anyendingstring")
For example, the following code
1 print("AAA", end = ' ')
2 print("BBB", end = ' ')
3 print("CCC", end = '*** ')
4 print("DDD", end = '*** ')
displays AAA BBBCCC***DDD***
Line 1 prints AAA followed by a space character ' ‘,
line 2 prints BBB, line 3 prints CCC followed by ***, and
line 4 prints DDD f
30
Escape Sequences for Special Characters
Now you can print the quoted message using the following
statement:
>>> print("He said, \"John's program is easy to read\"")
He said, "John's program is easy to read"
Note that the symbols \ and " together represent one
character.
31
Escape Sequences for Special Characters
For example,
radius = 3
print("The area is", radius * radius * math.pi, end = ' ')
print("and the perimeter is", 2 * radius)
Output:
The area is 28.26 and the perimeter is 6
32
The str Function
The str function can be used to convert a number into
a string. For example,
>>> s = str(3.4) # Convert a float to string
>>> s
'3.4'
>>> s = str(3) # Convert an integer to string
>>> s
'3'
>>>
33
The String Concatenation Operator
You can use the + operator add two numbers.
The + operator can also be used to concatenate
(combine) two strings. Here are some examples:
1 >>> message = "Welcome " + "to " + "Python"
2 >>> message
3 'Welcome to Python’
4 >>> chapterNo = 3
5 >>> s = "Chapter " + str(chapterNo)
6 >>> s
7 'Chapter 3’
8 >>>
34
Line 1 concatenates three strings into one.
In line 5, the str function converts the numeric
value in variable chapterNo to a string.
This string is concatenated with "Chapter " to
obtain the new string "Chapter 3".
35
The augmented assignment += operator
can also be used for string concatenation.
For example, the following code concatenates the
string in message with the string " and Python is
fun".
36
Reading Strings from the Console
To read a string from the console, use the
input function. For example, the following code reads
three strings from the keyboard:
s1 = input("Enter a string: ")
s2 = input("Enter a string: ")
s3 = input("Enter a string: ")
print("s1 is " + s1)
print("s2 is " + s2)
print("s3 is " + s3)
37
Reading Strings from the Console
38
Case Study: Minimum Number of Coins
Program lets the user enter the amount in decimal
representing dollars and cents and output a report
listing the monetary equivalent in single dollars,
quarters, dimes, nickels, and pennies.
Your program should report the maximum number of
dollars, then the number of quarters, dimes, nickels,
and pennies, in this order, to result in the minimum
number of coins
39
Case Study: Minimum Number of Coins
Here are the steps in developing the program:
1. Prompt the user to enter the amount as a decimal number, such as 11.56.
2. Convert the amount (11.56) into cents (1156).
3. Divide the cents by 100 to find the number of dollars. Obtain the
remaining cents using the cents remainder % 100.
4. Divide the remaining cents by 25 to find the number of quarters. Obtain
the remaining cents using the remaining cents remainder % 25.
5. Divide the remaining cents by 10 to find the number of dimes. Obtain the
remaining cents using the remaining cents remainder % 10.
6. Divide the remaining cents by 5 to find the number of nickels. Obtain the
remaining cents using the remaining cents remainder % 5.
7. The remaining cents are the pennies.
8. Display the result.
40
Program 3.3 Compute_Change.py
# Receive the amount
amount = eval(input("Enter an amount, for example, 11.56: "))
# Convert the amount to cents
remainingAmount = int(amount * 100)
# Find the number of one dollars
numberOfOneDollars = remainingAmount // 100
remainingAmount = remainingAmount % 100
# Find the number of quarters in the remaining amount
numberOfQuarters = remainingAmount // 25
remainingAmount = remainingAmount % 25
# Find the number of dimes in the remaining amount
numberOfDimes = remainingAmount // 10
remainingAmount = remainingAmount % 10
41
Program 3.3 Compute_Change.py
# Find the number of nickels in the remaining amount
numberOfNickels = remainingAmount // 5
remainingAmount = remainingAmount % 5
# Find the number of pennies in the remaining amount
numberOfPennies = remainingAmount
# Display the results
print("Your amount", amount, "consists of\n",
"\t", numberOfOneDollars, "dollars\n",
"\t", numberOfQuarters, "quarters\n",
"\t", numberOfDimes, "dimes\n",
"\t", numberOfNickels, "nickels\n",
"\t", numberOfPennies, "pennies")
42
Program 3.3 Compute_Change.py
Output:
Enter an amount, for example, 11.56: 34.56
Your amount 34.56 consists of
34 dollars
2 quarters
0 dimes
1 nickels
1 pennies
43
Introduction to Objects and Methods
In Python, all data—including numbers and
strings—are actually objects.
In Python, a number is an object, a string is an
object, and every datum is an object.
Objects of the same kind have the same type.
You can use the id function and type function to get
these pieces of information about an object.
44
Object Types and Ids
The id and type functions are rarely used in
programming, but they are good pedagogical tools for
understanding objects.
>>> n = 3 # n is an integer >>> s = "Welcome" # s is a string
>>> id(n) >>> id(s)
505408904 36201472
>>> type(n) >>> type(s)
<class ’int’> <class ’str’>
>>> f = 3.0 # f is a float
>>> id(f)
26647120
>>> type(f)
<class ’float’>
45
OOP and str Objects
The id and type functions are rarely used in
programming, but they are good pedagogical tools for
understanding objects.
46
Object vs. Object reference Variable
For n = 3, we say n is an integer variable that
holds value 3.
Strictly speaking, n is a variable that references an
int object for value 3.
For simplicity, it is fine to say n is an int variable
with value 3.
47
Methods
You can perform operations on an object.
The operations are defined using functions.
The functions for the objects are called methods
in Python. Methods can only be invoked from a
specific object.
For example, the string type has the methods such as
lower() and upper(), which returns a new string in
lowercase and uppercase.
Here are the examples to invoke these methods:
48
str Object Methods
Line 2 invokes s.lower() on object s to return a new string in
lowercase and assigns it to s1.
Line 5 invokes s.upper() on object s to return a new string in
uppercase and assigns it to s2.
As you can see from the preceding example, the syntax to
invoke a method for an object is object.method().
49
Striping beginning and ending
Whitespace Characters
Another useful string method is strip(), which can
be used to remove (strip) the
whitespace characters from both ends of a string.
The characters ' ', \t, \f, \r, and \n are known as the
whitespace characters.
50
Formatting Numbers and Strings
Often it is desirable to display numbers in certain
format. For example, the following code computes the
interest, given the amount and the annual interest rate.
The format function formats a number or a string and
returns a string.
format(item, format-specifier)
51
Because the interest amount is currency, it is desirable to display only
two digits after the digit.
However, the format is still not correct. There should be two digits
after the decimal point like 16.40 rather than 16.4. You can fix it by
using the format function
52
The syntax to invoke this function is
format(item, format-specifier)
where item is a number or a string and format-specifier is
a string that specifies how the item is formatted.
The function returns a string.
53
Formatting Floating-Point Numbers
54
Formatting Floating-Point Numbers
print(format(57.467657, '10.2f')) format specifier
10 . 2 f
print(format(12345678.923, '10.2f'))
print(format(57.4, '10.2f'))
field width conversion code
print(format(57, '10.2f'))
precision
10
□□□□□57.47
12345678.92
□□□□□57.40
□□□□□57.00
55
Formatting in Scientific Notation
If you change the conversion code from f to e, the
number will be formatted in scientific notation.
For example,
print(format(57.467657, '10.2e'))
print(format(0.0033923, '10.2e'))
10
print(format(57.4, '10.2e'))
□□5.75e+01
print(format(57, '10.2e'))
□□3.39e-03
□□5.74e+01
□□5.70e+01
56
Formatting as a Percentage
You can use the conversion code % to format numbers
as a percentage. For example,
print(format(0.53457, '10.2%'))
print(format(0.0033923, '10.2%'))
10
print(format(7.4, '10.2%'))
□□□□53.46%
print(format(57, '10.2%')) □□□□□0.34%
□□□740.00%
□□5700.00%
57
Justifying Format
By default, the format is right justified. You can put the
symbol < in the format specifier to specify that the item
is a left justified in the resulting format within the
specified width. For example,
print(format(57.467657, '10.2f'))
print(format(57.467657, '<10.2f'))
10
□□□□□57.47
57.47
58
Formatting Integers
You can use the conversion code d, x, o, and b to format
an integer in decimal, hexadecimal, octal, or binary.
You can specify a width for the conversion.
For example,
print(format(59832, '10d')) 10
print(format(59832, '<10d'))
□□□□□59832
print(format(59832, '10x')) 59832
print(format(59832, '<10x')) □□□□□□e9b8
e9b8
59
Formatting Integers
The format specifier 10d specifies
that the integer is formatted into a
decimal with a width of ten spaces.
The format specifier 10x specifies
that the integer is formatted into a
hexadecimal integer with a width
of ten spaces.
60
Formatting Strings
You can use the conversion code s to format a string
with a specified width. For example,
print(format("Welcome to Python", '20s'))
print(format("Welcome to Python", '<20s'))
print(format("Welcome to Python", '>20s'))
The format specifier 20s specifies that
the string is formatted within a width of
20. By default, a string is left justified.
20 To right-justify it, put the symbol > in
Welcome to Python the format specifier. If the string is
longer than the specified width, the
Welcome to Python width is automatically increased to fit
□□□Welcome to Python the string
61
Formatting Strings
62
Summary of Format Specifiers
63
Drawing Various Shapes
A turtle contains methods for moving the pen and
setting the pen’s size and speed.
64
Turtle Pen Drawing State Methods
65
Turtle Motion Methods
66
Turtle Motion Methods
The circle method has three arguments:
turtle.circle(r, ext, step)
The radius is required, and extent and step are optional.
extent is an angle that determines which part of the circle is
drawn. Step determines the number of steps to use.
If step is 3, 4, 5, 6, ..., the circle method will draw a maximum
regular polygon with three, four, five, six, or more sides
enclosed inside the circle (that is, a triangle, square, pentagon,
hexagon, etc.).
If step is not specified, the circle method will draw a circle.
67
Problem: Draw Simple Shapes
68
Program 3.4 Simple Shapes.py
import turtle
# Set pen thickness to 3 pixels
# Pull the pen up
# Pull the pen down
turtle.penup() # Draw a triangle
turtle.goto(-100, -50)
turtle.pendown()
turtle.circle(40, steps = 4) # Draw a square
turtle.penup()
turtle.goto(0, -50)
turtle.pendown()
69
Program 3.4 Simple Shapes.py
turtle.circle(40, steps = 5) # Draw a pentagon
turtle.penup()
turtle.goto(100, -50)
turtle.pendown()
turtle.circle(40, steps = 6) # Draw a hexagon
turtle.penup()
turtle.goto(200, -50)
turtle.pendown()
turtle.circle(40) # Draw a circle
turtle.done()
70
Turtle Drawing with Colors and Fonts
71
Drawing with Colors and Fonts
A turtle object contains the methods for setting colors and fonts.
72
Program 3.5 Color_Shapes.py
import turtle
turtle.pensize(3) # Set pen thickness to 3 pixels
turtle.penup() # Pull the pen up
turtle.goto(-200, -50)
turtle.pendown() # Pull the pen down
# Begin to fill color in a shape
turtle.circle(40, steps = 3) # Draw a triangle
# Fill the shape
turtle.penup()
turtle.goto(-100, -50)
turtle.pendown()
turtle.begin_fill() # Begin to fill color in a shape
turtle.color("blue")
turtle.circle(40, steps = 4) # Draw a square
turtle.end_fill() # Fill the shape
turtle.end_fill() # Fill the shape
73
Program 3.5 Color_Shapes.py
turtle.penup()
turtle.goto(0, -50)
turtle.pendown()
turtle.begin_fill() # Begin to fill color in a shape
turtle.color("green")
turtle.circle(40, steps = 5) # Draw a pentagon
turtle.end_fill() # Fill the shape
turtle.penup()
turtle.goto(100, -50)
turtle.pendown()
turtle.begin_fill() # Begin to fill color in a shape
turtle.color("yellow")
turtle.circle(40, steps = 6) # Draw a hexagon
74
Program 3.5 Color_Shapes.py
turtle.end_fill() # Fill the shape
turtle.penup()
turtle.goto(200, -50)
turtle.pendown()
turtle.begin_fill() # Begin to fill color in a shape
turtle.color("purple")
turtle.circle(40) # Draw a circle
turtle.end_fill() # Fill the shape
turtle.color("green")
turtle.penup()
turtle.goto(-100, 50)
turtle.pendown()
turtle.write("Cool Colorful Shapes",font = ("Times", 18, "bold"))
turtle.hideturtle()
turtle.done()
75
76