def main(): f = open('actor2.txt', 'r') previous_year = '' for line in f: nomination = line.split(',') if nomination[0] != previous_year: print nomination[1] previous_year = nomination[0] f.close() main()
If something is mutable, it means that it can be changed. In Python, lists are mutable, but strings are not. Example:
>>> x = 'hello' >>> x 'hello' >>> x[0] = 'j' Traceback (most recent call last): File "<pyshell#22>", line 1, in <module> x[0] = 'j' TypeError: 'str' object does not support item assignment
If we convert x into a list of characters instead, we can indeed change the h to a j:
>>> x = list(x) >>> x ['h', 'e', 'l', 'l', 'o'] >>> x[0] = 'j' >>> x ['j', 'e', 'l', 'l', 'o']
The caveat is now our string is not a string. To convert it back:
>>> x = ''.join(x) >>> x 'jello'
raw_input(), like input(), can be used to retrieve input. However, raw_input() behaves differently:
>>> x = raw_input('input something: ') input something: test >>> x 'test' >>> x = input('input something: ') input something: 'test' >>> x 'test' >>> x = raw_input('input something: ') input something: 0.5 >>> x '0.5' >>> x = input('input something: ') input something: 0.5 >>> x 0.5
Case-sensitive string comparison can be done in the same way you compare numbers:
>>> 'bob' == 'bob' True >>> 'bob' == 'BOB' False
For today's problem, however, you need to deal with strings that may not be in the same case. If the user inputs “bob”, you still want it to be basically the same as “BOB”. One easy way is to compare the lowercase version of these strings:
>>> x = 'bob' >>> y = 'bob' >>> z = 'BOB' >>> x.lower() == y.lower() True >>> x.lower() == z.lower() True
Download one of the files to use as your database:
Enter the actor: tom hanks Tom Hanks was nominated for an Oscar in 1988 for Big as Josh Baskin Tom Hanks won an Oscar in 1993 for Philadelphia as Andrew Beckett Tom Hanks won an Oscar in 1994 for Forrest Gump as Forrest Gump Tom Hanks was nominated for an Oscar in 1998 for Saving Private Ryan as Captain John H. Miller Tom Hanks was nominated for an Oscar in 2000 for Cast Away as Chuck Noland
def main(): f = open('actor2.txt', 'r') prev_year = 0 actor = raw_input('Enter the actor: ') for line in f: nomination = line.split(',') nomination[0] = int(nomination[0]) if nomination[1].lower() == actor.lower(): if prev_year != nomination[0]: print nomination[1], 'won an Oscar in', nomination[0], 'for', nomination[2] else: print nomination[1], 'was nominated for an Oscar in', nomination[0], 'for', nomination[2] if nomination[0] != prev_year: prev_year = nomination[0] f.close() main()