- What is the difference between str and
repr methods?
Ans: str returns a user friendly string representation of an object suitable for
end users; repr returns
a technical string representation, suitable for
developers. For example:
s = "dog"
print(str(s), repr(s))
# Output:
dog 'dog'
dog is the simple, user friendly output, 'dog' is the "technical" output that uses single quotes.
- What is the official type of a file object? Hint: use the standalone
type method:
fin = open("input.txt", "r")
print(type(fin))
# <class '_io.TextIOWrapper'>
- What is a Python list? How do you access individual items in a list?
Ans: A Python list is an ordered collection of items, for example
a = ["dog", 123, True, 3.456]
print(a)
# Output:
['dog', 123, True, 3.456]
Ans: Access the items in the list using a zero-based index:
print(a[2])
# Output:
True
- How does the str method split work?
(Not covered on midterm, but needed for Project 3)
Ans: The string split method returns a list of the fields in a comma delimited string.
For example:
line = "Alice,F,11"
print(line)
# Output:
Alice,F,11
fields = line.split(",")
print(fields)
# Output:
['Alice', 'F', 11]
We can then assign names to the fields like this:
name = fields[0].strip( )
gender = fields[1].strip( )
age = int(fields[2].strip( ))
print(name, gender, age)
# Output:
Alice F 11
the strip method removes leading and training whitespace (spaces, tabs, or new line characters) from the fields.
- What is the general form of a sequential processing script?
Ans: Here is the pseudocode:
initialize summary variable(s) (Could be count, sum, product, max, min)
open input file
read and throw away header lines (if any)
read first line
while line not blank
extract field(s) from line
assign variables from fields
update summary variables
read another line from input file
end
output summary information
- Write a sequential processing script that reads values from the file
kids.txt and computes the average of the girls' ages.
Ans: Here is a script that does this.