CSCE 110 Programming I Basics of Python (Part 3): Functions, Lists, For Loops, and Tuples Dr. Tiffani L. Williams Department of Computer Science and Engineering Texas A&M University Spring 2014 Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 1 / 21
Defining a Function A function is a named block of statements that performs an operation. To define a function, we use the following syntax: def func(param_list): block When executed, this compound statement creates a new function object and assigns it to the name func. func is a valid Python name (think of valid variable names), param_list represents zero or more comma-separated parameters, and block is an indented block of statements. Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 2 / 21
Function Examples (1) Listing 1: function-example.py 1 # A simple example of how to use functions 2 3 def print_msg (): 4 print "I love Python!" 5 6 def iseven ( num ): 7 print num % 2 == 0 8 9 print_msg () 10 iseven (10) 11 iseven (7) Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 3 / 21
Function Examples (2) Listing 2: temperature-converter.py 1 # Converts the temperature to Celsius or Fahrenheit 2 3 def to_fahrenheit (c): # Convert celsius to fahrenheit 4 return (c * 9.0/5.0) + 32 5 6 def to_celsius (f): # Convert fahrenheit to celsius 7 return (f - 32) * 5.0/9.0 8 9 type = raw_input (" Convert temperature to Celsius or Fahrenheit (c or f)? ") 10 if type == c : 11 temperature = int ( raw_input (" Enter Fahrenheit temperature : ")) 12 celsius = to_celsius ( temperature ) 13 print "%d Fahrenheit is %d Celsius." % ( temperature, celsius ) 14 else : 15 temperature = int ( raw_input (" Enter Celsius temperature : ")) 16 fahrenheit = to_fahrenheit ( temperature ) 17 print "%d Celsius is %d Fahrenheit." % ( temperature, fahrenheit ) Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 4 / 21
Function Examples (3) Listing 3: temperature-converter2.py 1 # Converts the temperature to Celsius or Fahrenheit. Uses a main function 2 # to drive the program. 3 4 def to_fahrenheit (c): # Convert celsius to fahrenheit 5 return (c * 9.0/5.0) + 32 6 7 def to_celsius (f): # Convert fahrenheit to celsius 8 return (f - 32) * 5.0/9.0 9 10 def main (): 11 type = raw_input (" Convert temperature to Celsius or Fahrenheit (c or f)? ") 12 if type == c : 13 temperature = int ( raw_input (" Enter Fahrenheit temperature : ")) 14 celsius = to_celsius ( temperature ) 15 print "%d Fahrenheit is %d Celsius." % ( temperature, celsius ) 16 else : 17 temperature = int ( raw_input (" Enter Celsius temperature : ")) 18 fahrenheit = to_fahrenheit ( temperature ) 19 print "%d Celsius is %d Fahrenheit." % ( temperature, fahrenheit ) 20 21 # Execution of the program begins here 22 main () Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 5 / 21
Built-in Functions abs() divmod() input() open() staticmethod() all() enumerate() int() ord() str() any() eval() isinstance() pow() sum() basestring() execfile() issubclass() print() super() bin() file() iter() property() tuple() bool() filter() len() range() type() bytearray() float() list() raw_input() unichr() callable() format() locals() reduce() unicode() chr() frozenset() long() reload() vars() classmethod() getattr() map() repr() xrange() cmp() globals() max() reversed() zip() compile() hasattr() memoryview() round() import () complex() hash() min() set() apply() delattr() help() next() setattr() buffer() dict() hex() object() slice() coerce() dir() id() oct() sorted() intern() Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 6 / 21
Local and Global Variables (1) Listing 4: local-global-variables.py 1 # An example showing the difference between local and global variables. 2 v = 15 # v is a global variable 3 4 def f1 (): 5 v = 17 # v is a local variable 6 print v(f1 ):, v 7 v = v + 1 8 print v(f1 ):, v 9 10 def f2 (): 11 print v(f2 ):, v # since v is not local, global version is used 12 13 f1 () 14 f2 () 15 print v:, v # references global version of v Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 7 / 21
Local and Global Variables (2) Listing 5: local-global-variables2.py 1 # This program has an error. Find it and explain why it is in fact an error. 2 3 v = 15 4 5 def f1 (): 6 v = 17 7 print v(f1 ):, v 8 9 def f2 (): 10 v = v + 10 11 print v(f2 ):, v 12 13 f1 () 14 f2 () 15 print v:, v Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 8 / 21
Lists Ordered collection of data. Example: some_data = [ dog, 78, 87.0, gorilla ] Elements can be of different types (heterogeneous) Can have a mixture of strings, ints, floats, lists, etc. Composed of elements that can be accessed by indexing Can create sublists by specifying an index range This is accomplished with the slicing operator [:] or [::] You can change individual elements directly ( mutable ) Unlike strings, each element in a list can be modified List creation operator [ ], elements of the list are separated by commas Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 9 / 21
List Examples (Python Shell) 1 >>> alist = [1, 2, 3, 4] # list creation 2 >>> alist 3 [1, 2, 3, 4] 4 5 >>> alist [0] # indexing individual elements 6 1 7 8 >>> alist [2:] # creating sublist 9 [3, 4] 10 11 >>> alist [:3] # creating sublist 12 [1, 2, 3] 13 14 >>> alist [1] = 5 # mutable 15 >>> alist 16 [1, 5, 3, 4] Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 10 / 21
List Examples (Python Shell) 1 >>> alist = [1, 2, 3, 4] # list creation 2 >>> alist 3 [1, 2, 3, 4] 4 5 >>> alist [0] # indexing individual elements 6 1 7 8 >>> alist [2:] # creating sublist 9 [3, 4] 10 11 >>> alist [:3] # creating sublist 12 [1, 2, 3] 13 14 >>> alist [1] = 5 # mutable 15 >>> alist 16 [1, 5, 3, 4] Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 11 / 21
for Loop for iter_var in iterable: suite_to_repeat Objects that are iterable include strings, lists, and tuples. Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 12 / 21
for Loop Examples Listing 6: for-example.py 1 for eachletter in " Names ": 2 print " current letter :", eachletter Listing 7: for-example2.py 1 name_list = [ Walter, " Nicole ", Steven ] # iterating over a list 2 for each_name in name_list : 3 print each_name, " Smith " Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 13 / 21
while vs for loops Listing 8: while-vs-for.py 1 # Shows the difference between while and for loops by 2 # printing the numbers from 1 to 5. 3 4 print " while loop : Printing the numbers from 1 to 5." 5 i = 1 6 while i < 6: # could also write while i <= 5: 7 print i 8 i += 1 9 10 print "\ nfor loop : Printing the numbers from 1 to 5." 11 for i in range (1,6): # range (1,6) creates the list [1, 2, 3, 4, 5] 12 print i Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 14 / 21
Integer to English Conversion Given an integer value, return a string with the equivalent English text of each digit. For example, an input of 89 results in eight-nine being returned. For an extra challenge, return English text with proper usage, i.e., eighty-nine. For this problem, restrict values to be between 0 and 1,000. Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 15 / 21
Integer to English (Version 1) I Listing 9: integer-to-english1.py 1 # A program that converts an integer between 0 and 1,000 to its English equivalent. 2 3 # Returns the English equivalent of the numbers 0 to 9. 4 def convert ( digit ): 5 6 if digit == 0 : 7 name = zero 8 elif digit == 1 : 9 name = one 10 elif digit == 2 : 11 name = two 12 elif digit == 3 : 13 name = three 14 elif digit == 4 : 15 name = four 16 elif digit == 5 : 17 name = five 18 elif digit == 6 : 19 name = six 20 elif digit == 7 : 21 name = seven 22 elif digit == 8 : 23 name = eight 24 else : 25 name = nine 26 27 return name Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 16 / 21
Integer to English (Version 1) II 28 29 30 # Obtains the user s input and farms the work. 31 def main (): 32 33 result = 34 number = raw_input ( Please enter an integer between 0 and 1000: ) 35 36 for digit in number : 37 result += convert ( digit ) + - 38 39 print %s is %s. % (number, result [: len ( result ) -1]) 40 41 42 # Execution begins here. 43 main () Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 17 / 21
Integer to English (Version 2) Listing 10: integer-to-english1a.py 1 # A program that converts an integer between 0 and 1,000 to its English equivalent. 2 # Easy version. 3 4 # Returns the English equivalent of the numbers 0 to 9. 5 def convert ( digit ): 6 name = [ zero, one, two, three, four, five, 7 six, seven, eight, nine ] 8 return name [int ( digit )] 9 10 11 # Obtains the user s input and farms the work. 12 def main (): 13 14 result = [] 15 number = raw_input ( Please enter an integer between 0 and 1000: ) 16 17 for digit in number : 18 result += [ convert ( digit )] 19 20 result = -.join ( result ) 21 22 print %s is %s. % ( number, result ) 23 24 main () Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 18 / 21
Tuples Tuples are similar to lists except for one important difference. Unlike lists, tuples are immutable. Example: some_data = ( dog, 78, 87.1, gorilla ) An element in a tuple cannot be changed. In that sense, both strings and tuples share the immutability criterion. Reason for immutability: you don t want variable s contents to be accidentally overwritten. Tuple creation operator ( ), elements of the list are separated by commas Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 19 / 21
Tuple Examples (Python Shell) 1 >>> atuple = ( robots, 77, 93, try ) # tuple creation 2 >>> atuple 3 ( robots, 77, 93, try ) 4 5 >>> atuple [:3] # creating subtuples 6 ( robots, 77, 93) 7 8 >>> atuple [1] = 5 # immutable 9 10 Traceback ( most recent call last ): 11 File "<string >", line 1, in <fragment > 12 TypeError : tuple object does not support item assignment Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 20 / 21
Concatenating Lists or Tuples Examples (Python Shell) 1 >>> alist = [1, 2, 3] # list creation 2 >>> alist + [4, 5] # list concatenation 3 [1, 2, 3, 4, 5] 4 5 >>> atuple = ( four, five ) # tuple creation 6 >>> atuple + ( six ) # immutable 7 Traceback ( most recent call last ): 8 File "<string >", line 1, in <fragment > 9 TypeError : can only concatenate tuple ( not " str ") to tuple 10 11 >>> alist # print alist 12 [1, 2, 3] 13 >>> atuple # print atuple 14 ( four, five ) 15 >>> alist + [ atuple ] # concatenate list and tuple as a list 16 [1, 2, 3, ( four, five )] 17 18 >>> alist + atuple # immutable 19 20 Traceback ( most recent call last ): 21 File "<string >", line 1, in <fragment > 22 TypeError : can only concatenate list (not " tuple ") to list Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring 2014 21 / 21