PythonIntermed

Download Report

Transcript PythonIntermed

CSC1018F:
Intermediate Python
Diving into Python Ch. 4
Think Like a Comp. Scientist Ch. 1-6
Lecture Outline
Recap of Intro to Python [week 1]
Basics:
Conditionals
Iteration
Introspection:
Optional and Named Arguments
Built-in Functions
Filtering Lists
and & or
Lambda Functions
Recap of Python Intro
Defining and documenting functions
Block structure by indenting
Native Datatypes:
Dictionary
List
Tuple
String Formatting
List Comprehension (Mapping)
Recap Exercise: Functions
Design a python function Dictize that will
take a tuple and return a dictionary with:
Values corresponding to the tuple elements and
Keys that take the form “key0”, “key1”, 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
Bits and Pieces
Strings:
Pseudo-mathematical operators +
(concatenation) and * (repetition) are valid
E.g., >>> "spam" * 3 => "spamspamspam"
Input:
There are built in functions to get keyboard input
raw_input(prompt)
• Accepts user input terminated by pressing return
• Returns the typed input as a string
• Prompt is a string displayed before accepting input
Conditionals
Comparison operators (==, >, <, >=, <=, !=) return
True (1) or False (0). Logical operators (and, or, not)
can combine boolean expressions
Conditionals:
if condition:
block1
With optional else clause
Chained Conditionals:
if condition1:
block1
elif condition2:
block2
else:
block3
Iteration
The while statement:
while condition:
block
Repeats block until condition is False
The for loop:
for value in string:
block
for char in fruit:
print char
Traverses every element of a list, tuple or string
A compact equivalent of certain forms of the while loop
Java-style ‘for’ loops can still be done
Optional and Named
Arguments
Function arguments can:
Have default values
Be called in any order
Syntax
def info(object, spacing = 10, collapse = 1)
Parameters called out of order must be named (e.g.,
object = newtuple)
Usage
info(li)
# spacing = 10, collapse = 1
info(li, 12)
# spacing = 12, collapse = 1
info(li, collapse = 0)
# spacing = 10
info(spacing = 15, object = li)# collapse = 1
Built-in Functions
Python has built-in functions that are part of the
core language (don’t need to be imported)
Full list available in the Python Library Reference
type
Returns the datatype of an arbitrary object
>>> type(obdchelper)
<type 'module'>
str
Very general conversion of any object of any type into a
string
>>> str(1)
'1'
>>> str(obdchelper)
"module 'obdchelper' from …"
Filtering Lists
An extension of list comprehension
Apply the mapping function to selected
elements
Syntax: [mapping_expression for element
in source_list if filter_expression]
Example:
[elem for elem in li if elem != 'b']
[elem for elem in li if li.count(elem)
== 1]
The weirdness of and & or
The logical operators can be applied to more than
just boolean expressions
They return one of the values being compared
0, '', [], (), {}, None are considered False,
everything else is True
and
Evaluated left to right. Returns the first False value, or the
last value
>>> 'a' and 'b' => 'b'
>>> '' and 'b' => ''
or
Evaluated left to right. Returns the first True value, or the last
value
>>> 'a' or 'b' => 'a'
>>> '' or 'b' => 'b'
The and-or trick
Statements of the form:
if x:
val = a
else
val = b
Can be converted into:
val = x and a or b
>>> 1 and "first" or "second" => "first"
>>> 0 and "first" or "second" => "second"
But watch out for ‘a’ being false
>>> 1 and "" or "second" => "second"
Solution: (1 and [a] or [b])[0]
Lambda Functions
One-line mini functions
Body of function can only be a single expression
Drop parentheses around arguments
Return keyword is implied
Function of the form:
def f(x):
return x*2
Become:
>>> g = lambda x: x*2
>>> g(3) => 6