ComputerSysAndProgramming_7
ComputerSysAndProgramming_7
a = 'apple'
b = 'banana'
print(a + b) # Displays applebanana
print(a == b) # Displays False
print(a < b) # Displays True
'Hi there!' H i t h e r e !
0 1 2 3 4 5 6 7 8
'Hi there!' H i t h e r e !
0 1 2 3 4 5 6 7 8
# Prints Hi there!
Summing with Strings
'Hi there!' H i t h e r e !
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
print(noVowels)
# Prints H thr!
The Subscript Operator
'Hi there!' H i t h e r e !
0 1 2 3 4 5 6 7 8
Alternatively, any character can be accessed using the subscript
operator []
'Hi there!' H i t h e r e !
0 1 2 3 4 5 6 7 8
>>> s[len(s) - 1]
'!'
An Index-Based Loop
'Hi there!' H i t h e r e !
0 1 2 3 4 5 6 7 8
for ch in s: print(ch)
'Hi there!' H i t h e r e !
0 1 2 3 4 5 6 7 8
s = 'Hi there!'
'Hi there!' H i t h e r e !
0 1 2 3 4 5 6 7 8
s = 'Hi there!'
A negative index counts
print(s[len(s) - 1]) backward from the last position
# or, believe it or not, in a sequence
print(s[-1])
Slicing Strings
Extract a portion of a string (a substring)
s = 'Hi there!'
print(s.find('there')) # Displays 3
s = 'Hi there!'
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
The ord and chr Functions
ord converts a single-character string to its ASCII value
print(ord('A')) # Displays 65
print(chr(65)) # Displays A
code = ""
for ch in source:
code = code + str(ord(ch)) + " "
print(code)
source = ""
for ascii in code.split():
source = source + chr(int(ascii))
print(source) # Displays I won't be here!
Files
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
Primary and Secondary Storage
Integrated Hard disk
circuits on CD
wafer-thin DVD
chips Flash
Three steps:
Open the file for input
Read the text and save it in a variable
Process the text
Opening a File
<a variable> = open(<a file name>, <a flag>)
text = myfile.read()
print(text)
while True:
line = myfile.readline()
if line == '':
break
print(line[:-1])
Four steps:
Open the file for output
Covert the data to strings, if necessary
Write the strings to the file
Close the file
Example: Write Text to a File
filename = input('Enter a file name: ')
myfile.close()
myfile.close()
D F F F D F
F F F D F
F F
os Functions
Function What It Does
os.getcwd() Returns the current working directory (string)
import os.path
if not os.path.exists(filename):
print('Error: the file not not exist!')
else:
myfile = open(filename, 'r')
print(myfile.read())
myfile.close()
Thank You