CF Chapter-007
CF Chapter-007
CF Chapter-007
C E – 119
Computing Fundamentals (CF)
Compiled By:
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
Reference Books:
1. Discovering Computers, Misty Vermaat and Susan Sebok,
Cengage Learning
https://sites.google.com/view/muzammil2050
5
Course Instructors
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))
Output:
exp(1.0) = 2.718281828459045
log(2.78) = 1.0224509277025455
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))
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
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'
Now you can print the quoted message using the following
statement:
31
Escape Sequences for Special Characters
For example,
radius = 3
Output:
32
The str Function
38
Case Study: Minimum Number of Coins
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
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
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
46
Object vs. Object reference Variable
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
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.
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
10
□□□□□57.47
12345678.92
□□□□□57.40
□□□□□57.00
55
Formatting in Scientific Notation
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
62
Summary of Format Specifiers
63
Drawing Various Shapes
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
69
Program 3.4 Simple Shapes.py
turtle.circle(40, steps = 5) # Draw a pentagon
turtle.penup()
turtle.goto(100, -50)
turtle.pendown()
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