Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSc 120 Introduction to Computer Programing II Adapted from slides by

Similar presentations


Presentation on theme: "CSc 120 Introduction to Computer Programing II Adapted from slides by"— Presentation transcript:

1 CSc 120 Introduction to Computer Programing II Adapted from slides by
Dr. Saumya Debray 01: Python review

2 this class in context

3 Computer programming write execute code programmer computer

4 Computer programming Python code (CSc 120) Python interpreter
Java code (CSc 210) Java compiler + JVM C code (CSc 352) C compiler (CSc 453) programmer operating system (CSc 452) computer

5 Computer programming this class Python code (CSc 120)
Python interpreter Java code (CSc 210) Java compiler + JVM C code (CSc 352) C compiler (CSc 453) programmer operating system (CSc 452) computer

6 getting started

7 Python language and environment
Language: Python 3 free download from documentation available at tutorial beginner's guide language reference setup and usage, HOWTOs, FAQs

8 Python language and environment
Programming environment: idle (or idle3) comes bundled with Python download provides: interactive Python shell debugger execution from a file

9 Surprises if coming from C, C++, Java
No variable declarations Indentation instead of {} Flexible for loop Built-in data structures (lists, dictionaries, tuples, sets) Arbitary-precision integers Devision differences Garbage collection (also in Java) no explicit allocation/deallocation

10 python review: variables, expressions, assignment

11 python basics >>> x = 4 >>> y = 5 >>> z = x + y >>> x 4 >>> y 5 >>> z 9 >>> y = z * 2 18 >>>

12 python basics >>> : python interpreter's prompt
>>> x = 4 >>> y = 5 >>> z = x + y >>> x 4 >>> y 5 >>> z 9 >>> y = z * 2 18 >>> >>> : python interpreter's prompt black: user input (keyboard) blue: python interpreter output

13 python basics >>> x = 4 >>> y = 5 >>> z = x + y >>> x 4 >>> y 5 >>> z 9 >>> y = z * 2 18 >>> variables

14 python basics >>> x = 4 >>> y = 5 >>> z = x + y >>> x 4 >>> y 5 >>> z 9 >>> y = z * 2 18 >>> expressions

15 python basics >>> x = 4 >>> y = 5 >>> z = x + y >>> x 4 >>> y 5 >>> z 9 >>> y = z * 2 18 >>> assignment statements

16 python basics >>> x = 4 >>> y = 5 >>> z = x + y >>> x 4 >>> y 5 >>> z 9 >>> y = z * 2 18 >>> typing in an expression causes its value to be printed

17 python basics >>> x = 4 >>> y = 5 >>> z = x + y >>> x 4 >>> y 5 >>> z 9 >>> y = z * 2 18 >>> variables: names begin with letter or '_' don't have to be declared in advance type determined at runtime expressions: all the usual arithmetic operators

18 Multiple (aka parallel) assignment
>>> >>> x, y, z = 11, 22, 33 >>> x 11 >>> y 22 >>> z 33 Assigns to multiple variables at the same time x1, x2, ..., xn = exp1, exp2, ..., expn Behavior: exp1, ..., expn evaluated (L-to- R) x1, ..., xn are assigned (L-to-R)

19 EXERCISE >>> x = 3 >>> y = 4 >>> z = (2*x – 1 == y+1) >>> z ← what value is printed out for z?

20 EXERCISE >>> x = 3 >>> y = 4 >>> sum, diff, prod = x + y, x – y, x * y >>> prod+diff ← what is the value printed out?

21 python review: reading user input I: input()

22 Reading user input I: input()
>>> x = input() >>> x '13579' >>> y = input('Type some input: ') Type some input: 23 >>> y '23' >>> z = input('More input: ') More input: 567 >>> z '567' >>>

23 Reading user input I: input()
>>> x = input() >>> x '13579' >>> y = input('Type some input: ') Type some input: 23 >>> y '23' >>> z = input('More input: ') More input: 567 >>> z '567' >>> input statement: reads input from the keyboard returns the value read (a string)

24 Reading user input I: input()
>>> x = input() >>> x '13579' >>> y = input('Type some input: ') Type some input: 23 >>> y '23' >>> z = input('More input: ') More input: 567 >>> z '567' >>> input statement: reads input from the keyboard returns the value read (a string) takes an optional argument if provided, serves as a prompt

25 Reading user input I: input()
>>> >>> x = input() 12 >>> x '12' >>> y = x / 2 Traceback (most recent call last): File "<pyshell#59>", line 1, in <module> y = x / 2 TypeError: unsupported operand type(s) for /: 'str' and 'int' the value read in is represented as a string string ≡ sequence of characters

26 Reading user input I: input()
>>> >>> x = input() 12 >>> x '12' >>> y = x / 2 Traceback (most recent call last): File "<pyshell#59>", line 1, in <module> y = x / 2 TypeError: unsupported operand type(s) for /: 'str' and 'int' the value read in is represented as a string string ≡ sequence of characters TypeError: indicate an error due to wrong type

27 Reading user input I: input()
>>> >>> x = input() 12 >>> x '12' >>> y = x / 2 Traceback (most recent call last): File "<pyshell#59>", line 1, in <module> y = x / 2 TypeError: unsupported operand type(s) for /: 'str' and 'int' >>> y = int (x) / 2 >>> y 6.0 the value read in is represented as a string string ≡ sequence of characters TypeError: indicates an error due to a wrong type Fix: explicit type conversion

28 python review: basics of strings

29 Basics of strings >>> x = "abcd" >>> y = 'efgh' >>> z = "efgh" >>>

30 Basics of strings >>> x = "abcd" >>> y = 'efgh' >>> z = "efgh" >>> either single-quotes (at both ends) or double-quotes (at both ends)

31 Basics of strings >>> text = input('Enter a string: ') Enter a string: abcdefghi >>> text 'abcdefghi' >>> text[0] 'a' >>> text[1] 'b' >>> text[27] Traceback (most recent call last): File "<pyshell#153>", line 1, in <module> text[27] IndexError: string index out of range >>> a string is a sequence (array) of characters we can index into a string to get the characters

32 Basics of strings >>> text = input('Enter a string: ') Enter a string: abcdefghi >>> text 'abcdefghi' >>> text[0] 'a' >>> text[1] 'b' >>> text[27] Traceback (most recent call last): File "<pyshell#153>", line 1, in <module> text[27] IndexError: string index out of range >>> a string is a sequence (array) of characters we can index into a string to get the characters indexing beyond the end of the string gives an IndexError error

33 Basics of strings >>> text = input('Enter a string: ') Enter a string: abcdefghi >>> text 'abcdefghi' >>> text[0] 'a' >>> text[1] 'b' >>> text[27] Traceback (most recent call last): File "<pyshell#153>", line 1, in <module> text[27] IndexError: string index out of range >>> a string is a sequence (array) of characters we can index into a string to get the characters each character is returned as a string of length 1 Intuitively, a character is a single letter, digit, punctuation mark, etc. E.g.: 'a' '5' '$'

34 Basics of strings >>> x = '0123456789' >>>
'0' >>> x[1] '1' >>> x[2] '2' >>> x[-1] '9' >>> x[-2] '8' >>> x[-3] '7' x[ i ] : if i  0 (i.e., non-negative values): indexing is done from the beginning of the string the first letter has index 0 x[ i ] : if i < 0 (i.e., negative values): indexing is done from the end of the string the last letter has index -1

35 Basics of strings >>> x = '0123456789' >>>
'0' >>> x[1] '1' >>> x[2] '2' >>> x[-1] '9' >>> x[-2] '8' >>> x[-3] '7' x[ i ] : if i  0 (i.e., non-negative values): indexing is done from the beginning of the string the first letter has index 0 x[ i ] : if i < 0 (i.e., negative values): indexing is done from the end of the string the last letter has index -1

36 EXERCISE >>> x = 'a' >>> x == x[0]
what do you think will be printed here?

37 EXERCISE >>> x = 'apple' >>> x[2] == x[-2]
what do you think will be printed here?

38 Basics of strings Inside a computer, a character is represented as a number (its "ASCII value")

39 Basics of strings Inside a computer, a character is represented as a number (its "ASCII value") the ASCII value of a digit is not the same as the digit itself: '5' ≠ 5

40 EXERCISE >>> x = 27 >>> y = 'x' >>> x == y
What do you think will be printed here? Why?

41 Basics of strings >>> x = input() abcDE_fgHIJ_01234 >>> x 'abcDE_fgHIJ_01234' >>> >>> len(x) 17 >>> y = x.lower() >>> y 'abcde_fghij_01234' >>> x = y.upper() >> x 'ABCDE_FGHIJ_01234' len(x) : length of a string x

42 Basics of strings >>> x = input() abcDE_fgHIJ_01234 >>> x 'abcDE_fgHIJ_01234' >>> >>> len(x) 17 >>> y = x.lower() >>> y 'abcde_fghij_01234' >>> x = y.upper() >> x 'ABCDE_FGHIJ_01234' len(x) : length of a string x x.lower(), x.upper() : case conversion on the letters in a string x note that non-letter characters are not affected

43 Basics of strings >>> x = input() abcDE_fgHIJ_01234 >>> x 'abcDE_fgHIJ_01234' >>> >>> len(x) 17 >>> y = x.lower() >>> y 'abcde_fghij_01234' >>> x = y.upper() >> x 'ABCDE_FGHIJ_01234' len(x) : length of a string x x.lower(), x.upper() : case conversion on the letters in a string x note that non-letter characters are not affected Python supports a wide variety of string operations see python_strings.htm

44 Basics of strings >>> x = input() abcdefgh >>> x 'abcdefgh' >>> x[3] 'd' >>> >>> x[3] = 'z' Traceback (most recent call last): File "<pyshell#193>", line 1, in <module> x[3] = 'z' TypeError: 'str' object does not support item assignment

45 Basics of strings >>> x = input() abcdefgh >>> x 'abcdefgh' >>> x[3] 'd' >>> >>> x[3] = 'z' Traceback (most recent call last): File "<pyshell#193>", line 1, in <module> x[3] = 'z' TypeError: 'str' object does not support item assignment strings are immutable, i.e., cannot be modified or updated

46 Basics of strings strings are immutable, i.e., cannot be modified or updated to "modify" a string, we have to create a copy of it with the appropriate part(s) replaced by the new values

47 Basics of strings strings are immutable, i.e., cannot be modified or updated to "modify" a string, we have to create a copy of it with the appropriate part(s) replaced by the new values these operations are called "slicing"

48 Basics of strings strings are immutable, i.e., cannot be modified or updated to "modify" a string, we have to create a copy of it with the appropriate part(s) replaced by the new values these operations are called "slicing" + applied to strings does concatenation

49 Basics of strings + applied to strings does concatenation

50 Basics of strings + applied to strings does concatenation
does repeated concatenation if one argument is a number generates an error otherwise

51 Basics of strings + applied to strings does concatenation
does repeated concatenation if one argument is a number generates an error otherwise not all arithmetic operators carry over to strings

52 EXERCISE >>> x = "whoa!" >>> y = x[2] * len(x) >>> z = x[3] + x[0] + y >>> z what is printed here? awooooo

53 EXERCISE >>> x = input() >>> y = x + x >>> int(x) == int(y) True what input value(s) will cause this to work as shown?

54 python review: conditionals

55 Conditional statements: if/elif/else

56 Conditional statements: if/elif/else
>>> var1 = input() 100 >>> var2 = input() 200 >>> x1 = int(var1) >>> x2 = int(var2) >>> >>> if x1 > x2: print('x1 is bigger than x2') elif x1 == x2: print('x1 and x2 are equal') else: print('x1 is smaller than x2') x1 is smaller than x2 if-statement syntax: if BooleanExpr : stmt elif BooleanExpr : elif … else: elifs are optional (use as needed)

57 Conditional statements: if/elif/else
>>> var1 = input() 100 >>> var2 = input() 200 >>> x1 = int(var1) >>> x2 = int(var2) >>> >>> if x1 > x2: print('x1 is bigger than x2') elif x1 == x2: print('x1 and x2 are equal') else: print('x1 is smaller than x2') x1 is smaller than x2 if-statement syntax: if BooleanExpr : stmt elif BooleanExpr : elif … else: elifs are optional (use as needed) else is optional

58 python review: while loops

59 Loops I: while

60 Loops I: while while-statement syntax:
while BooleanExpr : stmt1 stmtn stmt1 … stmtn are executed repeatedly as long as BooleanExpr is True

61 python review: lists (aka arrays)

62 Lists

63 Lists a list (or array) is a sequence of values

64 Lists a list (or array) is a sequence of values
accessing list elements (i.e., indexing), computing length: similar to strings non-negative index values ( 0) index from the front of the list the first element has index 0 negative index values index from the end of the list the last element has index -1

65 EXERCISE >>> x = [ “abc”, “def”, “ghi”, “jkl” ] >>> x[1] + x[-1] what do you think will be printed here?

66 Lists a list (or array) is a sequence of values
accessing list elements (i.e., indexing), computing length: similar to strings lists are mutable, i.e., can be modified or updated different from strings

67 Lists a list (or array) is a sequence of values
accessing list elements (i.e., indexing), computing length: similar to strings lists are mutable, i.e., can be modified or updated different from strings slicing : similar to strings

68 Lists concatenation (+ and *) : similar to strings

69 Lists concatenation (+ and *) : similar to strings
these operators create “shallow” copies due to list mutability, this can cause unexpected behavior

70 Lists concatenation (+ and *) : similar to strings
these operators create “shallow” copies due to list mutability, this can cause unexpected behavior x 12 34 56 y shallow copying 12 34 56

71 Lists concatenation (+ and *) : similar to strings
these operators create “shallow” copies due to list mutability, this can cause unexpected behavior x 12 34 56 y after y[0].append(78) 12 34 56 78

72 Lists: sorting sort() : sorts a list

73 Lists: sorting sort() : sorts a list
sorted() : creates a sorted copy of a list; the original list is not changed

74 Lists: sorting sort() : sorts a list
sorted() : creates a sorted copy of a list; the original list is not changed the optional argument reverse specifies ascending or descending order

75 python review: lists ↔ strings

76 Strings → lists split() : splits a string on whitespace
returns a list of strings

77 Strings → lists split() : splits a string on whitespace
returns a list of strings split(delim) : given an optional argument delim, splits the string on delim

78 Lists → strings delim.join(list) : joins the strings in list
using the string delim as the delimiter returns a string

79 String trimming what if we wanted to get rid of the punctuation?

80 String trimming x.strip() : removes whitespace from
either end of the string x returns a string

81 String trimming x.strip() : removes whitespace from
either end of the string x x.strip(string) : given an optional argument string, removes any character in string from either end of x

82 String trimming x.strip() : removes whitespace from
either end of the string x x.strip(string) : given an optional argument string, removes any character in string from either end of x rstrip(), lstrip() : similar to strip() but trims from one end of the string

83 String trimming what if we wanted to get rid of the punctuation?
iterate over the list use strip() to trim each word in the list reassemble the trimmed words into a list

84 String trimming what if we wanted to get rid of the punctuation?
iterate over the list use strip() to trim each word in the list reassemble the trimmed words into a list

85 python review: functions

86 Functions def fn_name ( arg1 , …, argn )
defines a function fn_name with n arguments arg1 , …, argn

87 Functions def fn_name ( arg1 , …, argn ) return expr
defines a function fn_name with n arguments arg1 , …, argn return expr optional returns the value of the expression expr to the caller

88 Functions def fn_name ( arg1 , …, argn ) return expr
defines a function fn_name with n arguments arg1 , …, argn return expr optional returns the value of the expression expr to the caller fn_name(expr1, …, exprn) calls fn_name with arguments expr1, …, exprn

89 python review: reading user input II: file I/O

90 Reading user input II: file I/O
suppose we want to read (and process) a file "this_file.txt"

91 Reading user input II: file I/O
open() the file read and process the file close() the file

92 Reading user input II: file I/O
fileobj = open(filename) filename: a string fileobj: a file object

93 Reading user input II: file I/O
fileobj = open(filename) filename: a string fileobj: a file object for var in fileobj: reads the file a line at a time assigns the line (a string) to var

94 Reading user input II: file I/O
fileobj = open(filename) filename: a string fileobj: a file object for var in fileobj: reads the file a line at a time assigns the line (a string) to var Note that each line read ends in a newline ('\n') character

95 Reading user input II: file I/O
at this point we've reached the end of the file so there's nothing left to read

96 Reading user input II: file I/O
at this point we've reached the end of the file so there's nothing left to read to re-read the file, we have to close it and then re-open it

97 Reading user input II: file I/O
at this point we've reached the end of the file so there's nothing left to read to re-read the file, we have to close it and then re-open it NOTE: we can use strip() to get rid of the newline character at the end of each line

98 Writing output to a file
open(filename, "w"): opens filename in write mode, i.e., for output

99 Writing output to a file
open(filename, "w"): opens filename in write mode, i.e., for output fileobj.write(string): writes string to fileobj

100 Writing output to a file
open(filename, "w"): opens filename in write mode, i.e., for output fileobj.write(string): writes string to fileobj open the file in read mode ("r") to see what was written

101 python review: tuples

102 Tuples a tuple is a sequence of values (like lists)

103 Tuples a tuple is a sequence of values (like lists)
tuples use parens () by contrast, lists use square brackets [ ] parens can be omitted if no confusion is possible special cases for tuples: empty tuple: () single-element tuple: must have comma after the element: (111,)

104 Tuples a tuple is a sequence of values (like lists)
tuples use parens () by contrast, lists use square brackets [ ] parens can be omitted if no confusion is possible special cases for tuples: empty tuple: () single-element tuple: must have comma after the element: (111,) indexing in tuples works similarly to strings and lists

105 Tuples computing a length of a tuple: similar to strings and lists

106 Tuples computing a length of a tuple: similar to strings and lists
computing slices of a tuple: similar to strings and lists

107 Tuples + and * work similarly on tuples as for lists and strings

108 Tuples iterating through the elements of a tuple: similar to lists and strings

109 Tuples iterating through the elements of a tuple: similar to lists and strings checking membership in a tuple: similar to lists and strings

110 Tuples tuples are not mutable

111 Sequence types: mutability
tuples are immutable

112 Sequence types: mutability
tuples are immutable lists are mutable (even if the list is an element of a [immutable] tuple)

113 Sequence types: mutability
tuples are immutable lists are mutable (even if the list is an element of a [immutable] tuple) strings are immutable (even if the string is an element of a [mutable] list)

114 Sequence types: mutability
1 2 tuple (immutable) x ( ) list (mutable) [ ] [ ] [ ] a string (immutable) c e d b

115 Sequence types: mutability
1 2 tuple (immutable) x ( ) list (mutable) updates [ ] [ ] [ ] a string (immutable) c e f d b

116 Why use tuples? At the implementation level, tuples are much simpler than lists: lists are mutable; tuples are immutable this means that the implementation can process tuples without having to worry about the possibility of updates lists have methods (e.g., append); tuples do not have methods Tuples can be implemented more efficiently than lists

117 Summary: sequence types
Sequence types include: strings, lists, and tuples The elements are: i, i+k, i+2k, ... Source:

118 EXERCISE >>> x = [ (1, 2, 3), (4, 5, 6), (7, 8, 9) ] >>> x[0][0] = (2, 3, 4) >>> x[0] = [ 2, 3, 4 ] what do you think will be printed out? what do you think will be printed out?

119 python review: dictionaries

120 Dictionaries A dictionary is like an array, but it can be indexed using strings (or numbers, or tuples, or any immutable type) the values used as indexes for a particular dictionary are called its keys think of a dictionary as an unordered collection of key : value pairs empty dictionary: {} It is an error to index into a dictionary using a non- existent key

121 Dictionaries empty dictionary

122 Dictionaries empty dictionary populating the dictionary
in this example, one item at a time

123 Dictionaries empty dictionary populating the dictionary
in this example, one item at a time looking up the dictionary (indexing)

124 Dictionaries empty dictionary populating the dictionary
in this example, one item at a time looking up the dictionary (indexing) looking at the dictionary we can use this syntax to populate the dictionary too

125 Dictionaries empty dictionary populating the dictionary
in this example, one item at a time looking up the dictionary (indexing) looking at the dictionary we can use this syntax to populate the dictionary too indexing with a key not in the dictionary is an error ( KeyError )

126 Dictionaries initializing the dictionary
in this example, several items at once

127 Dictionaries initializing the dictionary
in this example, several items at once getting a list of keys in the dictionary useful since it’s an error to index into a dictionary with a key that is not in it

128 Dictionaries We can use a for loop to iterate through a dictionary

129 Dictionaries We can use a for loop to iterate through a dictionary
Notice that this iteration may not list the items in the dictionary in the same order as when they were inserted

130 EXERCISE >>> crs_units = { 'csc 352' : 3, 'csc 120': 4, 'csc 110': 4 } >>> for crs in print( "{0} : {1} units".format( crs, crs_units[crs] ) csc 110 : 4 units csc 120 : 4 units csc 352 : 3 units >>> How can we get the dictionary contents to be printed out in sorted order of the keys? (I.e., what goes in the box?)


Download ppt "CSc 120 Introduction to Computer Programing II Adapted from slides by"

Similar presentations


Ads by Google