Characters, Strings, and Lists Flashcards
Calculate the number of digits in a number. Find the bug:
»> n = 1234
»> len(n)
>>> n = 1234 >>> len(n) TypeError: object of type 'int' has no len() >>> len(str(n)) # correction 4
Calculate the number of digits in a negative number. Find the bug:
»> n = -42
»> len(str(n))
>>> n = -42 >>> len(str(n)) 3 (wrong, should be 2) >>> len(str(abs(n))) """abs() returns absolute value of operand""" 2
How do you do multiline comments? What is wrong with it?
Triple quotation mark (“”” or ‘’’) but it is unconventional and should be avoided.
What is the FIRST comment that should be present in a Python program?
What does this program do
What is the SECOND comment that should be present in a Python program?
Author(s): who wrote me
What is the THIRD comment that should be present in a Python program?
Date created
What is the FOURTH comment that should be present in a Python program?
Date modified and reason
What comments should key variables and user-defined functions have?
All key variables and user-defined functions should have comments explaining what they are used for.
What is ‘indexing’ a string?
Return a single character at a particular location (indexes start at 0, not 1)
What is string ‘slicing’?
Extracting a substring of arbitrary length
What is string ‘splitting’?
Breaking up a string into components based on particular substrings.
Complete the code:
»> string = “It was a dark”
»> string[4]
???
> > > string = “It was a dark”
string[4]
a
Complete the code:
»> string = “It was a dark”
»> string[-8]
???
Complete the code:
»> string = “It was a dark”
»> string[-8]
s
What is the general index for the LAST character in a string using positive numbers?
n-1, because indexes start at 0 from the left Eg: >>> name = "Levi" >>> name[4] IndexError: string index out of range >>> name[3] 'i'
What is the general index for the LAST character in a string using negative numbers?
-1, because indexes start at -1 (not 0) from the right Eg: >>> city = "Melbourne" >>> city[-0] 'L' >>> city[-1] 'e'