View
220
Download
0
Category
Tags:
Preview:
Citation preview
CSC231
1
Devon M. SimmondsUniversity of North Carolina, Wilmington
TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office hours: TR 1-2pm or by appointment. Office location: CI2046. Email: simmondsd[@]uncw.edu
Course Overview
CSC231
2
Python Overview
Outline Programming fundamentals
Programming Procedural and data abstractions Information hiding Algorithms
CSC231
3
Outline Cont’d Overview of Python
Python program structure Built-in atomic data types Built-in collection types Input and output Control structures Exception handling Functions Classes
Summary & Review
Python Overview
CSC231
4
Software Development Process
Requirement Specification
System Analysis
System Design
Testing
Implementation
Maintenance
Deployment
CSC231
5
Requirement Specification Requirement Specification
System Analysis
System Design
Testing
Implementation
Maintenance
Deployment
A formal process that seeks to understand the problem and document in detail what the software system needs to do. This phase involves close interaction between users and designers.
Most of the examples in this book are simple, and their requirements are clearly stated. In the real world, however, problems are not well defined. You need to study a problem carefully to identify its requirements.
CSC231
6
System AnalysisRequirement Specification
System Analysis
System Design
Testing
Implementation
Maintenance
Deployment
Seeks to analyze the business process in terms of data flow, and to identify the system’s input and output.
Part of the analysis entails modeling the system’s behavior. The model is intended to capture the essential elements of the system and to define services to the system.
CSC231
7
System Design
Requirement Specification
System Analysis
System Design
Testing
Implementation
Maintenance
Deployment
The process of designing the system’s components.
This phase involves the use of many levels of abstraction to decompose the problem into manageable components, identify classes and interfaces, and establish relationships among the classes and interfaces.
CSC231
8
IPO Requirement Specification
System Analysis
System Design
Input, Process, Output
Testing
Implementation
Maintenance
Deployment The essence of system analysis and design is input, process, and output. This is called IPO.
CSC231
9
Implementation Requirement Specification
System Analysis
System Design
Testing
Implementation
Maintenance
Deployment
The process of translating the system design into programs. Separate programs are written for each component and put to work together.
This phase requires the use of a programming language like Python. The implementation involves coding, testing, and debugging.
CSC231
10
Testing Requirement Specification
System Analysis
System Design
Testing
Implementation
Maintenance
Deployment
Ensures that the code meets the requirements specification and weeds out bugs.
An independent team of software engineers not involved in the design and implementation of the project usually conducts such testing.
CSC231
11
Deployment Requirement Specification
System Analysis
System Design
Testing
Implementation
Maintenance
Deployment
Deployment makes the project available for use.
CSC231
12
Maintenance Requirement Specification
System Analysis
System Design
Testing
Implementation
Maintenance
Deployment
Maintenance is concerned with changing and improving the product.
A software product must continue to perform and improve in a changing environment. This requires periodic upgrades of the product to fix newly discovered bugs and incorporate changes.
CSC231
So software development or Software Engineering require that we… Analyze Design Code Test Deploy Maintain
Software programs
13
Software Development Process
CSC231
What is a program?
A sequence of instructions written in machine language that tells the CPU to take action (e.g., add two numbers) in a specific order
Programming is the act of writing a program.
Programming Fundamentals 14
CSC231
How a Program Works CPU designed to perform simple operations on pieces of
data Examples: reading data, adding, subtracting,
multiplying, and dividing numbers Understands instructions written in machine
language and included in its instruction set Each brand of CPU has its own instruction set
To carry out meaningful calculation, CPU must perform many operations
15Programming Fundamentals
CSC231 Identifiers: Names for Things
Identifiers: names for data, functions, and other items used in a program. Str1, num1,
str2, num2, input, sum, print
Variable: a location in memory Used to store
data, code Variables are
given names: identifiers
''' Python program to input and add two numbers''' # Get the first numberstr1 = input("Please enter 1st number: ")num1 = int(str1)#Convert str1 to int
# Get the second numberstr2 = input ("Please enter 2nd number: ")num2 = int(str1)#Convert str1 to int
# Add the two numberssum = num1 + num2
# Print the resultprint ("The sum is: ", sum)
16Programming Fundamentals
CSC231
Identifiers & Variables Variable names (i.e., identifiers) are
used to access and manipulate data stored in memory An identifier references the value it
represents Assignment statement: used to create a
variable and make it reference data General format is identifier = expression
Example: age = 29 Assignment operator: the equal sign (=) 17Programming Fundamentals
CSC231
18
Variables in Algorithms
Variables are simply a name given to represent a place in memory.
0x000
0x001
0x002
0x003
0x004
0x005
0x006
0x007
Memory addresses
How do we instruct the computer to put a value at a specific
address?
By assigning a name to each
address that we want to use.
Programming Fundamentals
num 44
CSC231
19
Rules for names of Identifiers
An identifier is a sequence of characters that consists of letters, digits, underscores (_), and asterisk (*).
An identifier must start with a letter or an underscore. It cannot start with a digit.
An identifier cannot be a reserved word. (See Appendix A, "Python Keywords," for a list of reserved words.) Reserved words have special meanings in Python, which we will later.
An identifier can be of any length.
Programming Fundamentals
CSC231
Comments Comments: notes of
explanation within a program Ignored by Python
interpreter Intended for a person
reading the program’s code
Multi-line comments: enclosed in a pair of three quote marks:
Single-line comments begin with a # character
End-line comment: appears at the end of a line of code
Typically explains the purpose of that line
''' Python program to input and add two numbers''' # Get the first numberstr1 = input("Please enter 1st number: ")num1 = int(str1)#Convert str1 to int
# Get the second numberstr2 = input ("Please enter 2nd number: ")num2 = int(str1)#Convert str1 to int
sum = num1 + num2 # Add the numbers
# Print the resultprint ("The sum is: ", sum) 20Programming Fundamentals
CSC231 Basic Tasks of a Program :
Typically, a program performs three types of tasks:
Input Receive Input (any data
that the program receives while it is running)
Processing Perform computation on
the input Output
Send results of computations to users
21
# Python program to add two numbers # Get the first numberstr1 = input("Please enter 1st number: ")num1 = int(str1)#Convert str1 to int
# Get the second numberstr2 = input ("Please enter 2nd number: ")num1 = int(str1)#Convert str1 to int
# Add the two numberssum = num1 + num2
# Print the resultprint ("The sum is: ", sum)
Programming Fundamentals
CSC231How a Program Works (cont’d.)
Program must be copied from secondary memory to RAM each time CPU executes it
CPU executes program in cycle: Fetch: read the next instruction from
memory into CPU Decode: CPU decodes fetched instruction to
determine which operation to perform Execute: perform the operation
22Programming Fundamentals
CSC231
23
The CPU performs the fetch, decode, execute cycle in order to process program information.
Fetch
FETCH: The CPU’s control unit fetches, from main memory,the next instruction in the sequence of program instructions.
Decode
DECODE: The instruction is encoded in the form of a number. The control unit decodes the instruction and generates an electronic signal.
ExecuteEXECUTE: The signal is routed to the appropriate component of the computer (such as the ALU, a disk drive, or some other device). The signal causes the component to perform an operation and store results in main memory.
How a Program Works (cont’d.)
Programming Fundamentals
CSC231
24
Procedural Abstraction
Encapsulating an algorithm in a programming unit so that the code cannot be directly manipulated from outside the unit. Called information hiding
Programming Fundamentals
CSC231
25
Non-Procedural
Programming
Code is written in strict sequential order. Functions/procedures/methods etc are not used.
Programming Fundamentals
''‘ NON_Procedural Program to create a dictionary of words from a datafile. ‘''
infile = open("AbrahamLincoln.txt", "r")matrix=infile.read().split(".")lineCount = 0wordDict = {}while (lineCount < len(matrix)): words = matrix[lineCount] words = words.strip() line = words.split() for word in line: if(word in wordDict): wordDict[word].append(lineCount) else: wordDict[word] = list(str(lineCount)) lineCount += 1print(wordDict)
CSC231
26
Procedural Abstraction
Encapsulating an algorithm in a programming unit so that the code cannot be directly manipulated from outside the unit.
Programming Fundamentals
''‘ Program to create a dictionary of words from a datafile. '''
def inputData(): infile = open("AbrahamLincoln.txt", "r") lines=infile.read().split(".") return lines
def processData(matrix): lineCount = 0 wordDict = {} while (lineCount < len(matrix)): words = matrix[lineCount] words = words.strip() line = words.split() for word in line: if(word in wordDict): wordDict[word].append(lineCount) else: wordDict[word] = list(str(lineCount)) index += 1 lineCount += 1 return wordDict def main(): matrix = inputData() wordDict = processData(matrix) print(wordDict)
main()
CSC231
27
Why study data structures and
algorithms? Execution time
So we can determine how fast/slow a program will execute.
Memory usage So we can determine how efficient
a program is in its use of memory.
Programming Fundamentals
CSC231
Integers Floating point numbers
Built-in Atomic Data Types
28
CSC231Numeric Data Types, Literals, and the str Data Type Data types: categorize value in memory
int for integer float for real number str used for storing strings in memory
Literals: numbers or strings written in a program Numeric literals: 12, 22.7 String literals: “To be or not to be”
29Built-in Atomic Data Types
CSC231
30
Assignment Statements
x = 1 # Assign 1 to x
x = x + 1
i = j = k = 1
CSC231
31
Simultaneous Assignment
var1, var2, ..., varn = exp1, exp2, ..., expn
x, y = y, x # Swap x with y
CSC231
32
Named Constants
The value of a variable may change during the execution of a program.
A a named constant or simply constant represents permanent data that never changes.
Python does not have a special syntax for naming constants. You can simply create a variable to denote a constant.
To distinguish a constant from a variable, use all uppercase letters to name a constant.
CSC231
33
Numeric Operators
Name Meaning Example Result
+ Addition 34 + 1 35 - Subtraction 34.0 – 0.1 33.9 * Multiplication 300 * 30 9000 / Float Division 1 / 2 0.5 // Integer Division 1 // 2 0 ** Exponentiation 4 ** 0.5 2.0 % Remainder 20 % 3 2
CSC231
34
Division and Remainder If both operands to the division operator (/) are
integers, the result is an integer (the fractional part is discarded)
The remainder operator (%) returns the remainder after dividing the second operand into the first
14 // 3 equals
8 // 12 equals
4
0
14 % 3 equals
8 % 12 equals
2
8
CSC231
35
Augmented Assignment Operators
Operator Example Equivalent
+= i += 8 i = i + 8
-= f -= 8.0 f = f - 8.0
*= i *= 8 i = i * 8
/= i /= 8 i = i / 8
%= i %= 8 i = i % 8
CSC231
36
Assignment Revisited The right and left hand sides of an assignment
statement can contain the same variable
First, one is added to theoriginal value of count
Then the result is stored back into count(overwriting the original value)
count = count + 1
CSC231
37
Assignment Operators
Often we perform an operation on a variable, and then store the result back into that variable
Python provides assignment operators to simplify that process
For example, the statement
num += count
is equivalent to
num = num + count
CSC231
38
Assignment Revisited The right and left hand sides of an assignment
statement can contain the same variable
First, count is added to theoriginal value of num
Then the result is stored back into num(overwriting the original value)
num += count (num = num + count)
CSC231
39
Assignment Operators
There are many assignment operators in Java, including the following:Operator
+=-=*=/=%=
Example
x += yx -= yx *= yx /= yx %= y
Equivalent To
x = x + yx = x - yx = x * yx = x / yx = x % y
CSC231
40
Overflow
When a variable is assigned a value that is too large (in size) to be stored, it causes overflow. For example, executing the following statement causes overflow.
>>>245.0 ** 1000
OverflowError: 'Result too large'
CSC231
41
Underflow
When a floating-point number is too small (i.e., too close to zero) to be stored, it causes underflow. Python approximates it to zero. So normally you should not be concerned with underflow.
CSC231
42
Scientific Notation
Floating-point literals can also be specified in scientific notation, for example, 1.23456e+2, same as 1.23456e2, is equivalent to 123.456, and 1.23456e-2 is equivalent to 0.0123456. E (or e) represents an exponent and it can be either in lowercase or uppercase.
CSC231
43
Arithmetic Expressions
)94
(9))(5(10
5
43
y
x
xx
cbayx
is translated to
(3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y)
CSC231
44
Type Conversion and Rounding
datatype(value)
i.e., int(4.5) => 4 float(4) => 4.0 str(4) => “4”
round(4.6) => 5round(4.5) => 4
CSC231 Reading Numbers with the input Function input function always returns a string
Format: variable = input(prompt) Prompt: instruction to user to enter a
value Built-in functions convert between data
types int(item) converts item to an int float(item) converts item to a float
str1 = input("Please enter a number: ") num1 = int(str1)#Convert str1 to int
Type conversion only works if item is valid numeric value, otherwise, throws exception
45
CSC231 Operator Precedence and Grouping with Parentheses
Python operator precedence:1. Operations enclosed in parentheses
Forces operations to be performed before others
2. Exponentiation (**)3. Multiplication (*), division (/ and //), and
remainder (%)4. Addition (+) and subtraction (-)
Higher precedence performed first Same precedence operators execute from left
to right46
CSC231
47
Operator Precedence What is the order of evaluation in the following
expressions?a + b + c + d + e
1 432a + b * c - d / e
3 241
a / (b + c) - d % e2 341
a / (b * (c + (d - e)))4 123
CSC231 Breaking Long Statements into Multiple Lines
Long statements cannot be viewed on screen without scrolling and cannot be printed without cutting off
Multiline continuation character (\): Allows to break a statement into multiple lines Example:
print(‘my first name is’,\ first_name) 48
CSC231 More About Data Output (cont’d.)
Special characters appearing in string literal Preceded by backslash (\)
Examples: newline (\n), horizontal tab (\t)
Treated as commands embedded in string
When + operator used on two strings in performs string concatenation Useful for breaking up a long string
literal
49
CSC231Expressions: Operators & Operands
Expressions are made up of operators and operands
Operators are special symbols that represent computations like addition and multiplication. The values the operator uses are called operands.
20+32, hour-1, hour*60+minute, minute/60, 5**2
num = 7k = 5val = 2print(num * k // val)
50
CSC231 Python Program Structure(functions but no class)
51
Heading comment Import statement function-1 function-2 function-3 …. main function Invocation of main function
CSC231 Python Program Structure(classes and functions)
52
Heading comment Import statement class-1 class-2 class-3 …. main function Invocation of main
function
Each class consist of: Heading comment Import statement function-1 function-2 function-3 ….
CSC231
Lists Strings Tuples Sets Dictionaries
Built-in Collection Data
Types
53
CSC231
Lists A list is an ordered collection of zero or more
references to Python data objects. Lists are written as comma-delimited values
enclosed in square brackets. The empty list is simply [ ].
54
CSC231
55
Creating Lists
list1 = list() # Create an empty listlist2 = list([2, 3, 4]) # Create a list with elements 2, 3, 4list3 = list(["red", "green", "blue"]) # Create a list with stringslist4 = list(range(3, 6)) # Create a list with elements 3, 4, 5list5 = list("abcd") # Create a list with characters a, b, c
list1 = [] # Same as list()list2 = [2, 3, 4] # Same as list([2, 3, 4]) list3 = ["red", "green"] # Same as list(["red", "green"])
Creating list using the list class
For convenience, you may create a list using the following syntax:
CSC231
56
list Methods
list
append(x: object): None
insert(index: int, x: object): None
remove(x: object): None
index(x: object): int
count(x: object): int
sort(): None
reverse(): None
extend(l: list): None
pop([i]): object
Add an item x to the end of the list.
Insert an item x at a given index. Note that the first element in the list has index 0.
Remove the first occurrence of the item x from the list.
Return the index of the item x in the list.
Return the number of times item x appears in the list.
Sort the items in the list.
Reverse the items in the list.
Append all the items in L to the list.
Remove the item at the given position and return it. The square bracket denotes that parameter is optional. If no index is specified, list.pop() removes and returns the last item in the list.
CSC231
57
Functions for lists>>> list1 = [2, 3, 4, 1, 32]>>> len(list1)5>>> max(list1)32>>> min(list1)1>>> sum(list1) 42>>> import random>>> random.shuffle(list1) # Shuffle the items in the list>>> list1[4, 1, 2, 32, 3]
CSC231
58
Indexer Operator []
5.6
4.5
3.3
13.2
4.0
34.33
34.0
45.45
99.993
11123
myList = [5.6, 4.5, 3.3, 13.2, 4.0, 34.33, 34.0, 45.45, 99.993, 11123]
myList reference myList[0]
myList[1]
myList[2]
myList[3]
myList[4]
myList[5]
myList[6]
myList[7]
myList[8]
myList[9]
Element value
list reference variable
list element at index 5
CSC231
59
The +, *, and in Operators >>> list1 = [2, 3]>>> list2 = [1, 9]>>> list3 = list1 + list2>>> list3[2, 3, 1, 9] >>> list3 = 2 * list1>>> list3[2, 3, 2, 3]>>> list1 = [2, 3, 5, 2, 33, 21]>>> 2 in list1True>>> list1 = [2, 3, 5, 2, 33, 21]>>> 2.5 in list1False
CSC231
60
The [ : ] Operator & list Slicing>>> list1 = [2, 3, 5, 2, 33, 21]>>> list1[-1]21>>> list1[-3]2>>> list1[2:5][5, 2, 33]
so List1[a, b] = [ list1[a], list1[a+1], … list1[b-1] ]
CSC231
61
The [ : ] Operator & list Slicing>>> list1 = [
[1,2,3,4,5,6,7], [8,9,19,11,12,13,14], [15,16,17,18,19,20,21]
]>>> list1[0][1,2,3,4,5,6,7]
>>> list1[2][15,16,17,18,19,20,21]
>>> list1[-1][15,16,17,18,19,20,21]
CSC231
62
The [ : ] Operator & list Slicing>>> list1 = [
[1,2,3,4,5,6,7], [8,9,19,11,12,13,14], [15,16,17,18,19,20,21]
]>>> list1[2:5][[15,16,17,18,19,20,21]]
>>> list1[::-1][[15, 16, 17, 18, 19, 20, 21], [8, 9, 19, 11, 12, 13,
14], [1, 2, 3, 4, 5, 6, 7]]
CSC231
63
List ComprehensionList comprehensions provide a concise way to create items from sequence. A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a list resulting from evaluating the expression. Here are some examples:
>>> list1 = [x for x in range(0, 5)]>>> list1 [0, 1, 2, 3, 4] >>> list2 = [0.5 * x for x in list1] >>> list2[0.0, 0.5, 1.0, 1.5, 2.0]>>> list3 = [x for x in list2 if x < 1.5]>>> list3[0.0, 0.5, 1.0]
CSC231
64
List ComprehensionList comprehensions provide a concise way to create items from sequence. A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a list resulting from evaluating the expression. Here are some examples:
>>> >>> squares = [] >>> for x in range(10):
... squares.append(x**2)
... >>> squares [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] is the same as>>> squares = [x**2 for x in range(10)]
>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
CSC231
65
Comparing Lists>>>list1 = [1, 1, 1, 1] >>>list2 = [1, 1, 1, 20] >>>list3 = [1, 2, 1, 1]
>>>list2 == list1False>>>list2 != list1True>>>list2 >= list1True>>>list2 > list1True>>>list3 < list2False
Based on lexicographical ordering
CSC231
66
Splitting a String to a List
items = "Welcome to the US".split() print(items)['Welcome', 'to', 'the', 'US']
items = "34#13#78#45".split("#")print(items)['34', '13', '78', '45']
CSC231
67
Copying Lists
Often, in a program, you need to duplicate a list or a part of a list. In such cases you could attempt to use the assignment statement (=), as follows: list2 = list1;
Contents of list1
list1
Contents of list2
list2
Before the assignment list2 = list1;
Contents of list1
list1
Contents of list2
list2
After the assignment list2 = list1;
Garbage
CSC231
68
Passing Lists to Functiosdef printList(lst): for element in lst: print(element)
Invoke the function
lst = [3, 1, 2, 6, 4, 2]printList(lst)
Invoke the functionprintList([3, 1, 2, 6, 4, 2])
Anonymous list
CSC231
69
Pass By Value
Python uses pass-by-value to pass arguments to a function. There are important differences between passing the values of variables of numbers and strings and passing lists.
Immutable objects Changeable objects
CSC231
70
Pass By Value (Immutable objects)
For an argument of a number or a string, the original value of the number and string outside the function is not changed, because numbers and strings are immutable in Python.
CSC231
71
Pass By Value (changeable objects)
For an argument of a list, the value of the argument is a reference to a list; this reference value is passed to the function. Semantically, it can be best described as pass-by-sharing, i.e., the list in the function is the same as the list being passed. So if you change the list in the function, you will see the change outside the function.
CSC231
72
Simple Example
def main(): x = 1 # x represents an int value y = [1, 2, 3] # y represents a list m(x, y) # Invoke f with arguments x and y print("x is " + str(x)) print("y[0] is " + str(y[0]))
def m(number, numbers): number = 1001 # Assign a new value to number numbers[0] = 5555 # Assign a new value to numbers[0]
main()
CSC231
73
Subtle Issues Regarding Default Arguments
def add(x, lst = []): if not(x in lst): lst.append(x) return lstlist1 = add(1)print(list1)list2 = add(2)print(list2)list3 = add(3, [11, 12, 13, 14])print(list3)list4 = add(4)print(list4)
[1][1, 2][11, 12, 13, 14, 3][1, 2, 4]
Output
default value is created only once.
CSC231
74
Subtle Issues Regarding Default Arguments
def add(x, lst = None): if(lst == None): lst = [] if not(x in lst): lst.append(x) return lst
Change the default list to [] for each function call.
CSC231
Lists Strings Tuples Sets Dictionaries
The String Collection Data
Type
75
CSC231
76
Strings and Characters
letter = 'A' # Same as letter = "A" numChar = '4' # Same as numChar = "4" message = "Good morning" # Same as message = 'Good morning'
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.
CSC231
77
NOTE
For consistency, some persons 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.
CSC231
78
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 is a small subset of Unicode.
CSC231
79
Functions ord and chr>>> ch = 'a'>>> ord(ch)>>> 97>>> chr(98)>>> 'b'
CSC231
80
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
CSC231
81
Printing without the Newline
print(item, end = 'anyendingstring')
print("AAA", end = ' ')print("BBB", end = '')print("CCC", end = '***')print("DDD", end = '***')
CSC231
82
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'>>>
CSC231
83
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:>>> message = "Welcome " + "to " + "Python">>> message 'Weclome to Python'>>> chapterNo = 2>>> s = "Chapter " + str(chapterNo)>>> s'Chapter 2'>>>
CSC231
84
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)
CSC231
85
Striping beginning and ending Whitespace Characters
Another useful string method is strip(), which can be used to strip the whitespace characters from the both ends of a string.
>>> s = "\t Welcome \n">>> s1 = s.strip() # Invoke the strip method>>> s1'Welcome'
CSC231
86
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)
CSC231
87
Formatting Floating-Point Numbers
10 . 2 f
print(format(57.467657, '10.2f'))
print(format(12345678.923, '10.2f'))
print(format(57.4, '10.2f'))
print(format(57, '10.2f'))
field width
precision
conversion code
format specifier
□□□□□57.47 12345678.92 □□□□□57.40 □□□□□57.00
10
CSC231
88
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'))print(format(57.4, '10.2e'))print(format(57, '10.2e'))
□□5.75e+01 □□3.39e-03 □□5.74e+01 □□5.70e+01
10
CSC231
89
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%'))print(format(7.4, '10.2%'))print(format(57, '10.2%'))
□□□□53.46% □□□□□0.34% □□□740.00% □□5700.00%
10
CSC231
90
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'))
□□□□□57.47 57.47
10
CSC231
91
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'))print(format(59832, '<10d'))print(format(59832, '10x'))print(format(59832, '<10x'))
□□□□□59832 59832 □□□□□□e9b8 e9b8
10
CSC231
92
Formatting StringsYou 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'))
Welcome to Python Welcome to Python □□□Welcome to Python
20
CSC231
93
The str Class
Creating Stringss1 = str() # Create an empty strings2 = str("Welcome") # Create a string
Welcome
Python provides a simple syntax for creating string using a string literal. For example,
s1 = "" # Same as s1 = str()s2 = "Welcome" # Same as s2 =
str("Welcome")
CSC231
94
Strings are ImmutableA string object is immutable. Once it is created, its contents cannot be changed. To optimize performance, Python uses one object for strings with the same contents. As shown in Figure 6.8, both s1 and s2 refer to the same string object. >>> s1 = "Welcome"
>>> s2 = "Welcome"
>>> id(s1)
505408902
>>> id(s2)
505408902
After executing s = "HTML";
: str
str object for "Welcome"
s1
s2
CSC231
95
Functions for str
>>> s = "Welcome">>> len(s)7>>> max(s)o>>> min(s)W
CSC231
96
Index Operator []
P r o g r a m m i ni
gi
0 1 2 3 4 5 6 7 8 9i
10i s
s[0] s[1] s[10]
CSC231
97
The +, *, [ : ], and in Operators
>>> s1 = "Welcome">>> s2 = "Python">>> s3 = s1 + " to " + s2>>> s3’Welcome to Python’>>> s4 = 2 * s1>>> s4’WelcomeWelcome’>>> s1[3 : 6]’com’>>> 'W' in s1True>>> 'X' in s1False
CSC231
98
Negative Index
>>> s1 = "Welcome">>> s1[-1] ‘e’>>> s1[-3 : -1]‘me’
CSC231
99
The in and not in Operators
>>> s1 = "Welcome" >>> "come" in s1True>>> "come" not in s1 False>>>
CSC231
100
Foreach Loops
for ch in string: print(ch)
for i in range(0, len(s), 2): print(s[i])
CSC231
101
Comparing Strings >>> s1 = "green">>> s2 = "glow">>> s1 == s2False>>> s1 != s2True>>> s1 > s2True>>> s1 >= s2True>>> s1 < s2False>>> s1 <= s2False
CSC231
102
Testing Characters in a String
str
isalnum(): bool
isalpha(): bool isdigit(): bool
isidentifier(): bool
islower(): bool
isupper(): bool
isspace(): bool
Return True if all characters in this string are alphanumeric and there is at least one character.
Return True if all characters in this string are alphabetic and there is at least one character.
Return True if this string contains only number characters.
Return True if this string is a Python identifier.
Return True if all characters in this string are lowercase letters and there is at least one character.
Return True if all characters in this string are uppercase letters and there is at least one character.
Return True if this string contains only whitespace characters.
CSC231
103
Searching for Substrings
str
endswith(s1: str): bool
startswith(s1: str): bool
find(s1): int
rfind(s1): int
count(subtring): int
Returns True if the string ends with the substring s1.
Returns True if the string starts with the substring s1.
Returns the lowest index where s1 starts in this string, or -1 if s1 is not found in this string.
Returns the highest index where s1 starts in this string, or -1 if s1 is not found in this string.
Returns the number of non-overlapping occurrences of this substring.
CSC231
104
Converting Strings
str
capitalize(): str
lower(): str
upper(): str
title(): str
swapcase(): str
replace(old, new): str
Returns a copy of this string with only the first character capitalized.
Returns a copy of this string with all characters converted to lowercase.
Returns a copy of this string with all characters converted to uppercase.
Returns a copy of this string with the first letter capitalized in each word.
Returns a copy of this string in which lowercase letters are converted to uppercase and uppercase to lowercase.
Returns a new string that replaces all the occurrence of the old string with a new string.
CSC231
105
Stripping Whitespace Characters
str
lstrip(): str
rstrip(): str
strip(): str
Returns a string with the leading whitespace characters removed.
Returns a string with the trailing whitespace characters removed.
Returns a string with the starting and trailing whitespace characters removed.
CSC231
106
Formatting Strings
str
center(width): str
ljust(width): str
rjust(width): str
format(items): str
Returns a copy of this string centered in a field of the given width.
Returns a string left justified in a field of the given width.
Returns a string right justified in a field of the given width.
Formats a string. See Section 3.6.
CSC231
On Your Own
Please review sets and tuples dictionaries
107
CSC231
108
What did we do in this class?
Lecture Summary
CSC231
Lists Strings Tuples Sets Dictionaries
Classes & Objects…
Algorithm Analysis
109
What’s next?
CSC231
110
______________________Devon M. Simmonds
Computer Science Department
University of North Carolina Wilmington
_____________________________________________________________
Qu es ti ons?
What are your course expectations? Reading for next class?
CSC231
Lists Strings Tuples Sets Dictionaries
Python Collection Data
Types: Tuples, Sets &
Dictionaries
111
What’s next?
Recommended