Python File I/O, Strings, Control Flow and Data Structures
Python File I/O, Strings, Control Flow and Data Structures
File Input Examples
infile.read(1)
'T'
>>>>
infile.read(5)
'he 3 '
>>>>
infile.readline()
'lines in this file end with the new line
character.\n'
>>>>
infile.read()
'\nThere is a blank line above this line.\n'
>>>>
infile.close()File Output Examples
outfile = open('test.txt', 'w')
>>>>
outfile.write('T')
1
>>>>
outfile.write('his is the first line.')
22
>>>>
outfile.write(' Still the first line...\n')
25
>>>>
outfile.write('Now we are in the second line.\n')
31
>>>>
outfile.write('Non string value like '+str(5)+' must be converted first.\n')
49
>>>>
outfile.write('Non string value like {} must be converted first.\n'.format(5))
49
>>>> outfile.close()Conditional Statements (If / Else)
if temp > 86:
print('It is hot!')
print('Be sure to drink liquids.')
else:
print('It is not hot.')
print('Bring a jacket.')
print('Goodbye.')BMI Function Example
def BMI(weight, height):
'prints BMI report'
bmi = weight * 703 / height**2
if bmi < 18.5:
print('Underweight')
elif bmi < 25:
print('Normal')
else: # bmi >= 25
print('Overweight')For Loops and Ranges
String Slicing and Methods
Link = '<a href="http://www.main.com/smith/index.html">http://www.main.com/smith/index.html</a>'
>>>> Link[:4]
'http'
>>>> Link[:4].upper()
'HTTP'
>>>> Link.find('smith')
20
>>>> Link[20:25]
'smith'
>>>> Link[20:25].capitalize()
'Smith'
>>>> Link.replace('smith','ferreira')
'<a href="http://www.main.com/ferreira/index.html">http://www.main.com/ferreira/index.html</a>'
>>>> Link
'<a href="http://www.main.com/smith/index.html">http://www.main.com/smith/index.html</a>'
>>>> New = Link.replace('smith','ferreira')
>>>> New
'<a href="http://www.main.com/ferreira/index.html">http://www.main.com/ferreira/index.html</a>'
>>>> Link.count('/')
4
>>>> Link.split('/')
['http:', '', 'www.main.com', 'smith', 'index.html']
Table = Str.maketrans(':,-' 3*' ')
Event.transl8(table)
'tuesdayFeb292012335Pm'
Event.transl8(table).split()
['tuesday', 'feb', '29', '2012', '3', '35', 'pm']Formatting and Print Examples
Print(prodCostWght2talSep=';')
Morels1390.569.5
Print(prodCostWght2talSep=':::')
Morels:::139:::0.5:::69.5
Print('{},{} {},{} @ {}:{}:{}'.4mat(weekdayMonth,
DayYearHourMinute2nd))
WednesdayMarch102012 @11:45:33List Iteration and String Formatting
Iterating Over Collections
for animal in pets:
print(animal, end=' ')
cat dog fish birdSorted Check Function (Pseudo / Corrected)
def checkSorted(lst):
'return True if sequence lst is increasing, False otherwise'
# iterate through indices and compare adjacent items
for i in range(len(lst) - 1):
# compare lst[i] with lst[i+1]
if lst[i] > lst[i+1]:
# incorrectly ordered, return False
return False
# all adjacent pairs are in order
return TrueArithmetic Sequence Check
def arithmetic(lst):
if len(lst) < 2:
# a sequence of length < 2 is arithmetic by definition
return True
# check that the difference between successive numbers is
# equal to the difference between the first two numbers
diff = lst[1] - lst[0]
for i in range(1, len(lst) - 1):
if lst[i+1] - lst[i] != diff:
return False
return TrueSum and Product Examples
Acronym and Divisors Functions
def acronym(phrase):
'return the acronym of the input string phrase'
# split phrase into a list of words
words = phrase.split()
# accumulate first character, as an uppercase, of every word
res = ''
for w in words:
res = res + w[0].upper()
return res
def divisors(n):
'return the list of divisors of n'
res = [] # accumulator initialized to an empty list
for i in range(1, n + 1):
if n % i == 0: # if i is a divisor of n
res.append(i) # accumulate i
return resNested Loops and 2D Printing
Finding First Negative and Row Processing
def greater(lst):
# iterate through list lst and
# compare each number with 0
# Using counter loop pattern
for i in range(len(lst)):
if lst[i] < 0:
# number at index i is first
# negative number, so return i
return i
# if no negative number is found, return None
return None
def before0(table):
for row in table:
for num in row:
if num == 0:
break
print(num, end=' ')
print()
>>>> before0(table)
2 3
4 5 6
def ignore0(table):
for row in table:
for num in row:
if num == 0:
continue
print(num, end=' ')
print()
>>>> ignore0(table)
2 3 6
3 4 5
4 5 6User-Defined Indexes and Dictionaries
User-defined indexes and dictionaries
Lookup and Frequency Examples
def complete(abbreviation):
'returns day of the week corresponding to abbreviation'
days = {
'Mo': 'Monday', 'Tu': 'Tuesday', 'We': 'Wednesday',
'Th': 'Thursday', 'Fr': 'Friday', 'Sa': 'Saturday',
'Su': 'Sunday'
}
return days[abbreviation]
def frequency(itemList):
'returns frequency of items in itemList'
counters = {}
for item in itemList:
if item in counters:
# increment item counter
counters[item] += 1
else:
# create item counter
counters[item] = 1
return countersAll examples and outputs preserved. Spelling and grammar corrected in explanatory text and comments. Code and outputs are shown as recorded interactive examples.
