80 likes | 228 Views
CSC1018F: Introduction to Python (Tutorial). James Gain jgain@cs.uct.ac.za Donald Cook dc@cs.uct.ac.za. Mini-Test (1). The Python statement x = "CSC" + 1018 + "F" will be rejected by the interpreter because of: Static typing Dynamic typing Strong typing Weak typing
E N D
CSC1018F: Introduction to Python (Tutorial) James Gain jgain@cs.uct.ac.za Donald Cook dc@cs.uct.ac.za
Mini-Test (1) • The Python statement x = "CSC" + 1018 + "F" will be rejected by the interpreter because of: • Static typing • Dynamic typing • Strong typing • Weak typing • In Python a function without a return statement, will return: • Nothing • The value None • The value False • The value Null
Mini-Test (2) • Is the following a valid Python program? • yes • no • Which of these statements do NOT apply to the Dictionary datatype? • Keys are case sensitive • Values can be of any datatype • Duplicate keys are permissible • Keys can be of any datatype • Dictionary elements have no ordering def test(n): if n > 10: return True return False
Mini-Test (3) • The square bracket notation (“[ ]”) is used in Python to: • Define a Dictionary • Define a List • Define a Tuple • Index a Dictionary Key • Index a List element • Index a Tuple element • Two lists can be combined with: • The ‘+’ operator • Extend • Append • Insert
Mini-Test (4) • Given the following Python statements: The output will be: • [1, 2, 3] • [2, 2, 3] • [1, 3, 3] • undefined >>> a = [1, 2, 3] >>> b = a >>> a[1] = a[1] + 1 >>> b
Tut Q1: Lists • You are given two lists (North and South) representing generals of the American Civil War • North = [“Grant”, “Sheridan”, “McClellan”, “Hood”] • South = [“Lee”, “Jackson”] • Write out the contents of each list after the following operations: • South.insert(len(South), North.pop()) • South.append(South[2:]) • South = South[:1] + South[2:] • North = South + North
Tut Q2: Functions • Design a python function Dictize that will take a tuple and return a dictionary with: • Values correponding to the tuple elements and • Keys that take the form “key1”, “key2”, etc. (where the number matches the tuple index) • Create a doc string for your function and use the tuple (“Cleese”, “Gilliam”, “Chapman”, “Jones”, “Idle”, “Palin”) as a test within the module Dictize
Tut Q3: Dictionaries and Mapping • You have a dictionary defined as: >>> translate = {"one":["un", "eins"], "two":["deux", "zwei"], "three":["trois", "drei"]} • Write Python statements to: • Add a new element "four":["quatre", "vier"] • Through list comprehension print out the dictionary in the format "one is un (in French) or eins (in German) and two is …” • Convert the dictionary to a list of sublists each of the form ["one", "un", "eins"]