2. Sequences
• Sequences are collections of data values that are
ordered by position
• A string is a sequence of characters
• A list is a sequence of any Python data values
• A tuple is like a list but cannot be modified
3. Examples
Strings contain characters
Tuples and lists can contain anything
a = 'apple'
b = 'banana'
print(a, b) # Displays apple banana
fruits = (a, b) # A tuple
print(fruits) # Displays ('apple', 'banana')
veggies = ['bean', 'lettuce'] # A list
print(veggies) # Displays ['bean', 'lettuce']
4. String Assignment,
Concatenation, and Comparisons
Strings can be ordered like they are in a dictionary
a = 'apple'
b = 'banana'
print(a + b) # Displays applebanana
print(a == b) # Displays False
print(a < b) # Displays True
5. Positions or Indexes
H i t h e r e !
Each character in a string has a unique position called its index
We count indexes from 0 to the length of the string minus 1
A for loop automatically visits each character in the string,
from beginning to end
'Hi there!'
0 1 2 3 4 5 6 7 8
for ch in 'Hi there!': print(ch)
6. Traversing with a for Loop
H i t h e r e !
A for loop automatically visits each character in the string,
from beginning to end
'Hi there!'
0 1 2 3 4 5 6 7 8
for ch in 'Hi there!': print(ch, end = '')
# Prints Hi there!
7. Summing with Strings
H i t h e r e !
Start with an empty string and add characters to it with +
'Hi there!'
0 1 2 3 4 5 6 7 8
noVowels = ''
for ch in 'Hi there!':
if not ch in ('a', 'e', 'i', 'o', 'u',
'A', 'E', 'I', 'O', 'U'):
noVowels += ch #noVowels = noVowels + ch
print(noVowels)
# Prints H thr!
8. The Subscript Operator
H i t h e r e !
Alternatively, any character can be accessed using the
subscript operator []
This operator expects an int from 0 to the length of the string
minus 1
Example:
Syntax:
'Hi there!'
0 1 2 3 4 5 6 7 8
<a string>[<an int>]
'Hi there!'[0] # equals 'H'
9. The len Function
H i t h e r e !
'Hi there!'
0 1 2 3 4 5 6 7 8
The len function returns the
length of any sequence
>>> len('Hi there!')
9
>>> s = 'Hi there!'
>>> s[len(s) - 1]
'!'
10. An Index-Based Loop
H i t h e r e !
If you need the positions during a loop, use the subscript
operator
'Hi there!'
0 1 2 3 4 5 6 7 8
s = 'Hi there!'
for ch in s: print(ch)
for i in range(len(s)): print(i, s[i])
11. Oddball Indexes
H i t h e r e !
To get to the last character in a string:
'Hi there!'
0 1 2 3 4 5 6 7 8
s = 'Hi there!'
print(s[len(s) - 1]) # Displays !
12. Oddball Indexes
H i t h e r e !
To get to the last character in a string:
'Hi there!'
0 1 2 3 4 5 6 7 8
s = 'Hi there!'
print(s[len(s) - 1])
# or, believe it or not,
print(s[-1])
A negative index counts
backward from the last position
in a sequence
13. Slicing Strings
s = 'Hi there!'
print(s[0:]) # Displays Hi there!
print(s[1:]) # Displays i there!
print(s[:2]) # Displays Hi (two characters)
print(s[0:2]) # Displays Hi (two characters)
Extract a portion of a string (a substring)
The number to the right of : equals one plus the
index of the last character in the substring
14. String Methods
A method is like a function, but the syntax for its use is
different:
s = 'Hi there!'
print(s.find('there')) # Displays 3
print(s.upper()) # Displays HI THERE!
print(s.replace('e', 'a')) # Displays Hi thara!
print(s.split()) # Displays ['Hi', 'there!']
<a string>.<method name>(<any arguments>)
15. String Methods
s = 'Hi there!'
print(s.split()) # Displays ['Hi', 'there!']
A sequence of items in [ ] is a Python list
16. Characters in Computer Memory
• Each character translates to a unique integer called its
ASCII value (American Standard for Information
Interchange)
• Basic ASCII ranges from 0 to 127, for 128 keyboard
characters and some control keys
17. The Basic ASCII Character Set
0 1 2 3 4 5 6 7 8 9
0 NUL SOH STX ETX EOT ENQ ACK BEL BS HT
1 LF VT FF CR SO SI DLE DC1 DC2 DC3
2 DC4 NAK SYN ETB CAN EM SUB ESC FS GS
3 RS US SP ! " # $ % & `
4 ( ) * + , - . / 0 1
5 2 3 4 5 6 7 8 9 : ;
6 < = > ? @ A B C D E
7 F G H I J K L M N O
8 P Q R S T U V W X Y
9 Z [ ] ^ _ ' a b c
10 d e f g h i j k l m
11 n o p q r s t u v w
12 x y z { | } ~ DEL
18. The ord and chr Functions
ord converts a single-character string to its ASCII value
chr converts an ASCII value to a single-character string
print(ord('A')) # Displays 65
print(chr(65)) # Displays A
for ascii in range(128): # Display 'em all
print(ascii, chr(ascii))
19. Data Encryption
A really simple (and quite lame) encryption algorithm
replaces each character with its ASCII value and a space
source = "I won't be here!"
code = ""
for ch in source:
code = code + str(ord(ch)) + " "
print(code)
# Displays 73 32 119 111 110 39 116 32 98 101 32 104 101 33
20. Data Decryption
To decrypt an encoded message, we split it into a list of
substrings and convert these ASCII values to the original
characters
source = ""
for ascii in code.split():
source = source + chr(int(ascii))
print(source) # Displays I won't be here!
22. Numeric Types: int
• int is used for integers
• In many languages, the range of int is -231 through
231 - 1 (-2,147,483,648 through 2,147,483,647)
• In Python, an integer’s magnitude is limited only by
the computer’s memory
23. Why 231 - 1?
• Numbers are stored in computer memory as patterns of
voltage levels
• Just two voltage levels, ON and OFF, are significant on a
digital computer
• ON and OFF represent the digits 1 and 0 of the binary
number system
• All numbers are represented in binary in a digital computer
25. Bits and Bytes
0 1 0 1 1 1 1 1 0 1 0 1 1 1 1 1 0 1 0 1 1 1 1 1 0 1 0 1 1 1 1 1
A byte is 8 bits
In some languages, int uses 4 bytes
The magnitude and the sign (+/-) of the number are
determined by the binary representation
byte byte byte byte
26. Decimal and Binary
• Decimal numbers use the 10 decimal digits and a base of
10
• Binary numbers use the binary digits 0 and 1 and a base of
2
• The base is often provided as a subscript to indicate the
type of system, as in 304210 and 110111102
• Thus, 110110 represents a very different integer value from
11012
27. Positional Notation
• Number systems are positional, so the magnitude of the number
depends on the base and the position of the digits in the number
• Each position represents a power of the number’s base
• For example, in a 3-digit decimal number, the three positions represent
the number of hundreds (102), tens (101), and ones (100)
• 342 = 3 * 102 + 4 * 101 + 2 * 100
• = 3 * 100 + 4 * 10 + 2 * 1
• = 300 + 40 + 2
• = 342
28. Positional Notation: Binary
• The base is now 2 and the only digits are 0 and 1
• Each position represents a power of 2
• For example, in a 4-digit binary number, the four positions represent
the number of eights (23), fours (22), twos (21), and ones (10)
• 1101 = 1 * 23 + 1 * 22 + 0 * 21 + 1 * 20
• = 1 * 8 + 1 * 4 + 0 * 2 + 1 * 1
• = 8 + 4 + 0 + 1
• = 13
29. An Algorithm for Binary to
Decimal Conversion
# Input: A string of 1 or more binary digits
# Output: The integer represented by the string
binary = input("Enter a binary number: ")
decimal = 0
exponent = len(binary) – 1
for digit in binary:
decimal = decimal + int(digit) * 2 ** exponent
exponent = exponent – 1
print("The integer value is", decimal)
The len function returns the number of
characters in a string
The for loop visits each character in a string
30. Counting in Binary
Binary Magnitude
0 0
1 1
10 2
11 3
100 4
101 5
110 6
111 7
1000 8
21
22
23
Each power of 2 in
binary is a 1 followed by
the number of 0s equal to
the exponent
What is the magnitude of
10000002?
31. Counting in Binary
Binary Magnitude
0 0
1 1
10 2
11 3
100 4
101 5
110 6
111 7
1000 8
21 - 1
22 - 1
23 - 1
Each number with only
1s equals one less than
the power of 2 whose
exponent is that number
of 1s
What is the magnitude of
11112?
32. Limits of Magnitude - Unsigned ints
• Unsigned integers are the non-negative integers
• The largest unsigned integer that can be
represented using N bits is 2N - 1 (all bits are 1s)
• Thus, the largest unsigned integer stored in 32 bits
is 232 - 1
33. Limits of Magnitude - Signed ints
• Signed integers include negative and positive integers and
0
• Part of the memory (one bit) must be reserved to represent
the number’s sign somehow
• For each bit unavailable, you must subtract 1 from the
exponent (2N-1) of the number’s magnitude
• Thus, the largest positive signed integer stored in 32 bits is
231 - 1
34. Twos Complement Notation
• Positive numbers have 0 in the leftmost bit, negative
numbers have 1 in the leftmost bit
• To compute a negative number’s magnitude,
– Invert all the bits
– Add 1 to the result
– Use the conversion algorithm
• To represent a negative number,
– Translate the magnitude to an unsigned binary number
– Invert all the bits
– Add 1 to the result
35. Convert Decimal to Binary
• Start with an integer, N, and an empty string, S
• Assume that N > 0
• While N > 0:
– Compute the remainder of dividing N by 2 (will be 0 or 1)
– Prepend the remainder’s digit to S
– Reset N to the quotient of N and 2
36. An Algorithm for Decimal to
Binary Conversion
# Input: An integer > 0
# Output: A string representing the integer in base 2
n = int(input("Enter an integer greater than 0: "))
binary = ''
while n > 0:
rem = n % 2
binary = str(rem) + binary
n = n // 2
print(binary)
Here we want the quotient and the remainder, not
exact division!
37. Numeric Types: float
• Uses 8 bytes to represent floating-point numbers
that range from +10308.25 through -10308.25
• Default printing is up to 16 digits of precision
• But actual precision seems to extend even further -
try format string with 60 places
38. Problems with Float
• Some numbers, such as 0.1, cannot be
represented exactly, due to round-off errors
• This can cause errors when two floats are
compared for equality
39. Example: Add 0.1 Ten Times
total = 0.0
for i in range(10):
total = total + 0.1
print(total) # Displays 1.0
print(total < 1.0) # Displays True!
Convert dollars and cents to pennies (ints) in
critical financial calculations!
40. Use int or float?
• In general, arithmetic operations are faster
with integers than with floats
• Integers (regular ones) require less memory
• Use float when it’s convenient to do so
and you’re not worried about losing
numeric information
42. Data Storage
• Data (and programs) are loaded into
primary memory (RAM) for processing
• From where?
– From input devices (keyboard, microphone)
– From secondary memory - a hard disk, a flash
stick, a CD, or a DVD
43. Primary and Secondary Storage
Primary
Memory (RAM)
Secondary
memory
Processor
I/O devices
Very fast
Expensive
Transient
Slower
Cheaper
Permanent
Keyboard
Mouse
Microphone
Monitor
Speakers
Hard disk
CD
DVD
Flash
Integrated
circuits on
wafer-thin
chips
44. What Is a File?
• A file is a software object that allows a program to
represent and access data stored in secondary memory
• Two basic types of files:
– Text files: for storing and accessing text (characters)
– Binary files: executable programs and their data files (such
as images, sound clips, video)
45. Text Files
• A text file is logically a sequence of characters
• Basic operations are
– input (read characters from the file)
– output (write characters to the file)
• There are several flavors of each type of operation
46. File Input
• We want to bring text in from a file for processing
• Three steps:
– Open the file for input
– Read the text and save it in a variable
– Process the text
47. Opening a File
<a flag> can be
'r' - used for input, to read from an existing file
'w' - used for output, to overwrite an existing file
'a' - used for output, to append to an existing file
<a variable> = open(<a file name>, <a flag>)
48. Example: Read Text from a File
The file name must either be in the current directory or
be a pathname to a file in a directory
Python raises an error if the file is not found
text refers to one big string
filename = input('Enter a file name: ')
myfile = open(filename, 'r')
text = myfile.read()
print(text)
49. Read Lines of Text from a File
The variable line picks up the next line of text on
each pass through the loop
line will contain the newline character, so the echo
will print extra blank lines
filename = input('Enter a file name: ')
myfile = open(filename, 'r')
for line in myfile:
print(line)
50. Read Lines of Text from a File
Extract a substring up to but not including the last
character (the newline)
This will produce an exact echo of the input file
filename = input('Enter a file name: ')
myfile = open(filename, 'r')
for line in myfile:
print(line[:-1])
51. Alternatively, Use readline
The readline method reads a line of text and
returns it as a string, including the newline character
This method returns the empty string if the end of file
is encountered
filename = input('Enter a file name: ')
myfile = open(filename, 'r')
while True:
line = myfile.readline()
if line == '':
break
print(line[:-1])
52. Count the Words
filename = input('Enter a file name: ')
myfile = open(filename, 'r')
wordcount = 0
for line in myfile:
wordcount += len(line.split())
print('The word count is', wordcount)
53. File Output
• We want to save data to a text file
• Four steps:
– Open the file for output
– Covert the data to strings, if necessary
– Write the strings to the file
– Close the file
54. Example: Write Text to a File
If the file already exists, it is overwritten; otherwise, it
is created in the current directory or path
The write method expects a string as an argument
Failure to close the file can result in losing data
filename = input('Enter a file name: ')
myfile = open(filename, 'w')
myfile.write('Two linesnof text')
myfile.close()
55. Example: Write Integers to a File
write can be called 0 or more times
Data values must be converted to strings before output
Separators, such as newlines or spaces, must be explicitly
written as well
filename = input('Enter a file name: ')
myfile = open(filename, 'w')
for i in range(1, 11):
myfile.write(str(i) + 'n')
myfile.close()
56. Managing Directories
• Directories are organized in a tree-like structure
• Python’s os module includes many functions for navigating through a
directory system and managing it
D
F F F D F
F D F
D
F F
F F
57. os Functions
Function What It Does
os.getcwd() Returns the current working directory (string)
os.chdir(path) Attaches to the directory specified by path
os.listdir(path) Returns a list of the directory’s contents
os.remove(name) Removes a file at path
os.rename(old, new) Resets the old path to the new one
os.removedirs(path) Removes the directory (and all subdirectories)
at path
58. os.path Functions
Function What It Does
os.path.exists(path) Returns True if path exists or False
otherwise.
os.path.isdir(path) Returns True if path names a directory or
False otherwise.
os.path.isfile(path) Returns True if path names a file or
False otherwise.
os.path.getsize(path) Returns the size of the object named by
path in bytes.
59. Example: Does the File Exist?
import os.path
filename = input('Enter a file name: ')
if not os.path.exists(filename):
print('Error: the file not not exist!')
else:
myfile = open(filename, 'r')
print(myfile.read())
myfile.close()