Download presentation
Presentation is loading. Please wait.
Published byHilda Payne Modified over 9 years ago
1
Devon M. Simmonds University of North Carolina, Wilmington
Course Overview Devon M. Simmonds University 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.
2
Python Overview Outline Programming fundamentals Programming
Procedural and data abstractions Information hiding Algorithms
3
Python Overview Outline Cont’d Overview of Python Summary & Review
Python program structure Built-in atomic data types Built-in collection types Input and output Control structures Exception handling Functions Classes Summary & Review
4
Software Development Process
5
Requirement Specification
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.
6
System Analysis 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.
7
System Design 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.
8
IPO The essence of system analysis and design is input, process, and output. This is called IPO.
9
Implementation 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.
10
Testing 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.
11
Deployment Deployment makes the project available for use.
12
Maintenance 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.
13
Software Development Process
So software development or Software Engineering require that we… Analyze Design Code Test Deploy Maintain Software programs
14
Programming Fundamentals
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
15
Programming Fundamentals
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 Programming Fundamentals
16
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 number str1 = input("Please enter 1st number: ") num1 = int(str1)#Convert str1 to int # Get the second number str2 = input ("Please enter 2nd number: ") num2 = int(str1)#Convert str1 to int # Add the two numbers sum = num1 + num2 # Print the result print ("The sum is: ", sum) Programming Fundamentals
17
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 (=) Programming Fundamentals
18
Variables in Algorithms
Variables are simply a name given to represent a place in memory. How do we instruct the computer to put a value at a specific address? num 0x000 0x001 0x002 0x003 0x004 0x005 0x006 0x007 44 Memory addresses By assigning a name to each address that we want to use. Programming Fundamentals
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
20
Programming Fundamentals
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 number str1 = input("Please enter 1st number: ") num1 = int(str1)#Convert str1 to int # Get the second number str2 = input ("Please enter 2nd number: ") num2 = int(str1)#Convert str1 to int sum = num1 + num2 # Add the numbers # Print the result print ("The sum is: ", sum) Programming Fundamentals
21
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 # Python program to add two numbers # Get the first number str1 = input("Please enter 1st number: ") num1 = int(str1)#Convert str1 to int # Get the second number str2 = input ("Please enter 2nd number: ") # Add the two numbers sum = num1 + num2 # Print the result print ("The sum is: ", sum) Programming Fundamentals
22
How 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 Programming Fundamentals
23
How a Program Works (cont’d.)
The CPU performs the fetch, decode, execute cycle in order to process program information. FETCH: The CPU’s control unit fetches, from main memory, the next instruction in the sequence of program instructions. Fetch DECODE: The instruction is encoded in the form of a number. The control unit decodes the instruction and generates an electronic signal. Decode Execute EXECUTE: 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. Programming Fundamentals
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
25
Non-Procedural Programming
''‘ NON_Procedural Program to create a dictionary of words from a datafile. ‘'' infile = open("AbrahamLincoln.txt", "r") matrix=infile.read().split(".") 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)) lineCount += 1 print(wordDict) Code is written in strict sequential order. Functions/procedures/methods etc are not used. Programming Fundamentals
26
Procedural Abstraction
''‘ 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() Procedural Abstraction Encapsulating an algorithm in a programming unit so that the code cannot be directly manipulated from outside the unit. Programming Fundamentals
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
28
Built-in Atomic Data Types
Integers Floating point numbers
29
Numeric 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” Built-in Atomic Data Types
30
Assignment Statements
x = # Assign 1 to x x = x + 1 i = j = k = 1
31
Simultaneous Assignment
var1, var2, ..., varn = exp1, exp2, ..., expn x, y = y, x # Swap x with y
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.
33
Numeric Operators
34
Division and Remainder
If both operands to the division operator (/) are integers, the result is an integer (the fractional part is discarded) 14 // equals 4 8 // equals The remainder operator (%) returns the remainder after dividing the second operand into the first 14 % equals 2 8 % equals 8
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
36
Assignment Revisited The right and left hand sides of an assignment statement can contain the same variable First, one is added to the original value of count count = count + 1 Then the result is stored back into count (overwriting the original value)
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
38
Assignment Revisited The right and left hand sides of an assignment statement can contain the same variable First, count is added to the original value of num num += count (num = num + count) Then the result is stored back into num (overwriting the original value)
39
Assignment Operators Operator += -= *= /= %= Example x += y x -= y
There are many assignment operators in Java, including the following: Operator += -= *= /= %= Example x += y x -= y x *= y x /= y x %= y Equivalent To x = x + y x = x - y x = x * y x = x / y x = x % y
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'
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.
42
Scientific Notation Floating-point literals can also be specified in scientific notation, for example, e+2, same as e2, is equivalent to , and e-2 is equivalent to E (or e) represents an exponent and it can be either in lowercase or uppercase.
43
Arithmetic Expressions
is translated to (3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y)
44
Type Conversion and Rounding
datatype(value) i.e., int(4.5) => 4 float(4) => 4.0 str(4) => “4” round(4.6) => 5 round(4.5) => 4
45
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
46
Operator Precedence and Grouping with Parentheses
Python operator precedence: Operations enclosed in parentheses Forces operations to be performed before others Exponentiation (**) Multiplication (*), division (/ and //), and remainder (%) Addition (+) and subtraction (-) Higher precedence performed first Same precedence operators execute from left to right
47
Operator Precedence What is the order of evaluation in the following expressions? a + b + c + d + e a + b * c - d / e 1 2 3 4 3 1 4 2 a / (b + c) - d % e 2 1 4 3 a / (b * (c + (d - e))) 4 3 2 1
48
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)
49
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
50
Expressions: 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 = 7 k = 5 val = 2 print(num * k // val)
51
Python Program Structure (functions but no class)
Heading comment Import statement function-1 function-2 function-3 …. main function Invocation of main function
52
Python Program Structure (classes and functions)
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 ….
53
Built-in Collection Data Types
Lists Strings Tuples Sets Dictionaries
54
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 [ ].
55
Creating Lists Creating list using the list class
list1 = list() # Create an empty list list2 = list([2, 3, 4]) # Create a list with elements 2, 3, 4 list3 = list(["red", "green", "blue"]) # Create a list with strings list4 = list(range(3, 6)) # Create a list with elements 3, 4, 5 list5 = list("abcd") # Create a list with characters a, b, c For convenience, you may create a list using the following syntax: list1 = [] # Same as list() list2 = [2, 3, 4] # Same as list([2, 3, 4]) list3 = ["red", "green"] # Same as list(["red", "green"])
56
list Methods
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]
58
Indexer Operator []
59
The +, *, and in Operators >>> list1 = [2, 3] >>> list2 = [1, 9] >>> list3 = list1 + list2 >>> list3 [2, 3, 1, 9] >>> list3 = 2 * list1 [2, 3, 2, 3] >>> list1 = [2, 3, 5, 2, 33, 21] >>> 2 in list1 True >>> 2.5 in list1 False
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] ]
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] >>> list1[-1]
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]]
63
List Comprehension List 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]
64
List Comprehension List 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)]
65
Comparing Lists >>>list1 = [1, 1, 1, 1]
>>>list2 == list1 False >>>list2 != list1 True >>>list2 >= list1 >>>list2 > list1 >>>list3 < list2 Based on lexicographical ordering
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("#") ['34', '13', '78', '45']
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;
68
Passing Lists to Functios
def printList(lst): for element in lst: print(element) Invoke the function lst = [3, 1, 2, 6, 4, 2] printList(lst) Invoke the function printList([3, 1, 2, 6, 4, 2]) Anonymous list
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
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.
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.
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()
73
Subtle Issues Regarding Default Arguments
def add(x, lst = []): if not(x in lst): lst.append(x) return lst list1 = add(1) print(list1) list2 = add(2) print(list2) list3 = add(3, [11, 12, 13, 14]) print(list3) list4 = add(4) print(list4) default value is created only once. Output [1] [1, 2] [11, 12, 13, 14, 3] [1, 2, 4]
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.
75
The String Collection Data Type
Lists Strings Tuples Sets Dictionaries
76
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'
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.
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.
79
Functions ord and chr >>> ch = 'a' >>> ord(ch)
>>> 97 >>> chr(98) >>> 'b'
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
81
Printing without the Newline
print(item, end = 'anyendingstring') print("AAA", end = ' ') print("BBB", end = '') print("CCC", end = '***') print("DDD", end = '***')
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 '3' >>>
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' >>>
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)
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'
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)
87
Formatting Floating-Point Numbers
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( , '10.2e')) print(format( , '10.2e')) print(format(57.4, '10.2e')) print(format(57, '10.2e'))
89
Formatting as a Percentage
You can use the conversion code % to format numbers as a percentage. For example, print(format( , '10.2%')) print(format( , '10.2%')) print(format(7.4, '10.2%')) print(format(57, '10.2%'))
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( , '10.2f')) print(format( , '<10.2f'))
91
Formatting Integers print(format(59832, '10d'))
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'))
92
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'))
93
The str Class Creating Strings
s1 = str() # Create an empty string s2 = 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")
94
Strings are Immutable A 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.
95
Functions for str >>> s = "Welcome" >>> len(s) 7
>>> max(s) o >>> min(s) W
96
Index Operator []
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 s1 True >>> 'X' in s1 False
98
Negative Index >>> s1 = "Welcome" >>> s1[-1] ‘e’
99
The in and not in Operators
>>> s1 = "Welcome" >>> "come" in s1 True >>> "come" not in s1 False >>>
100
Foreach Loops for ch in string: print(ch)
for i in range(0, len(s), 2): print(s[i])
101
Comparing Strings >>> s1 = "green" >>> s2 = "glow"
False >>> s1 != s2 True >>> s1 > s2 >>> s1 >= s2 >>> s1 < s2 >>> s1 <= s2
102
Testing Characters in a String
103
Searching for Substrings
104
Converting Strings
105
Stripping Whitespace Characters
106
Formatting Strings
107
On Your Own Please review sets and tuples dictionaries
108
Lecture Summary What did we do in this class?
109
Classes & Objects…Algorithm Analysis
What’s next? Classes & Objects…Algorithm Analysis Lists Strings Tuples Sets Dictionaries
110
Qu es ti ons? What are your course expectations?
Reading for next class? Qu es ti ons? ______________________ Devon M. Simmonds Computer Science Department University of North Carolina Wilmington _____________________________________________________________
111
Python Collection Data Types: Tuples, Sets & Dictionaries
What’s next? Python Collection Data Types: Tuples, Sets & Dictionaries Lists Strings Tuples Sets Dictionaries
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.