A thorough introduction to Python
Download
Report
Transcript A thorough introduction to Python
A thorough introduction to
Python
What is Python exactly?
Python is a modern rapid development language.
– Emphasizes single, intuitive approach to most
problems.
– Code is very clean and easy to read.
– Datatypes are both strong and dynamic (we’ll discuss
this in a minute)
– Highly object oriented – everything is an object, and
all objects support introspection and modification at
run time (we’ll discuss this more later)
When should you use Python?
• When the amount of time the program takes
to write is more important than the amount of
time it takes to run (this is usually the case!)
• When you expect to have to go back and look
at the source code for some reason at some
point in the future.
• When you want to spend more time thinking
about the solution than the code to
implement it.
Basic data types
The basics
• Integer – These are equivalent to long in c/c++.
• Float – These are equivalent to doubles in c/c++.
• String – These behave like an ordered collection of
characters.
• Complex – These are basically paired floats,
representing the real and imaginary portions of the
number.
• Boolean – Python’s boolean values are True and False.
• Null – python’s null type is referenced using the
keyword None.
Collection types
There are three main families of collection in Python:
• Sequence – ordered collection of elements
– Lists are mutable, denoted by square brackets (e.g. [1, 2,
3])
– Tuples are immutable, denoted by parentheses (e.g. (1, 2,
3))
• Set – collection of elements, none of which may be
represented more than once.
• Mapping – collection of keys elements and their
associated values elements.
– Dictionary, denoted by curly braces (e.g. {“foo”:1, “bar”:2})
Other notable types
• Type – When you create a class, it is actually an
instance of the Type type.
• Functions – Your standard discrete piece of code.
• Exceptions – When your program fails in a semipredictable manner, it will use these to let you
know.
• Modules – These represent a single namespace.
• Packages – These are collections that hold
modules, and allow you to arrange namespaces
hierarchically.
Basic language structure
Python abandons many of the common language
formatting idioms.
• Linefeed terminates a command – no semicolon
required (there are a couple of easy ways to span
multiple lines if you want to do so).
• No curly braces are required around subroutines
– Simply use a consistent indent for the
subroutine, and return to your previous
indentation level when the subroutine is
complete!
• “#” denotes the start of a single line comment.
Basic numerical operations
•
•
•
•
“+”, “-”, “*”, “/”, “%” (modulo) and “**” (power-of) all
behave roughly as expected.
If you perform any of these operations on two different
types of numbers (integer and float for example) the
number with the less expressive type is cast to the more
expressive type, and the result is also of that type.
“=“ assigns the value on the right to the variable on the
left.
The “+=“, “-=“, “*=“, “/=“ and “**=“perform the indicated
operation between the variable on the left and the value
on the right, then assign the result to the variable on the
left.
Basic condition tests
• “==“ tests to see if two things have the same
value. “!=“ tests to see if two things have a
different value.
• The “<“, “>”, “<=“, “>=“ all compare relative
values.
• “is” tests to see if two things have the same
identity.
• “in” tests element membership in a
collection.
Basic flow control
Python provides flow control using if, for and
while statements.
for and while loops support break and continue
statements, which are identical to their
c/java counterparts. Additionally, these
statements support an optional else clause.
The do … while syntax is not available in python.
if Statement
Perhaps the most well-known statement type is the if statement. For
example:
There can be zero or more elif parts, and the else part is optional. The
keyword ‘elif‘ is short for ‘else if’, and is useful to avoid excessive
indentation. An if ... elif ... elif ... sequence is a substitute for the
switch or case statements found in other languages.
for Statement
The for statement in Python differs a bit from what you may
be used to in C or Pascal. Rather than always iterating over
an arithmetic progression of numbers (like in Pascal), or
giving the user the ability to define both the iteration step
and halting condition (as C), Python’s for statement iterates
over the items of any sequence (a list or a string), in the
order that they appear in the sequence. For example (no
pun intended):
break and continue Statements, and
else Clauses on Loops
The break statement, like in C, breaks out of the smallest enclosing for or while loop.
The continue statement, also borrowed from C, continues with the next iteration of the loop.
Loop statements may have an else clause; it is executed when the loop terminates through exhaustion
of the list (with for) or when the condition becomes false (with while), but not when the loop is
terminated by a break statement. This is exemplified by the following loop, which searches for
prime numbers:
Boolean operators
Any value, other than None, False, 0, an empty string, or an empty
collection evaluates to True in a boolean context.
The boolean operators supported by python, in order of increasing
precedence, are:
• “and”
• “or”
• “not”
The boolean “and” and “or” operators in python have slightly unusual
behavior. Roughly speaking, the boolean operator returns the value
that causes the operator to succeed or fail. This behavior is
powerful when understood. Note that this does not apply to “not”
operator, which returns True or False.
More on boolean operators
A quick example of Python’s unusual boolean behavior, assuming A evaluates to True,
B evaluates to True and C evaluates to False.
•
•
•
•
•
•
•
•
A and B returns B, and is True
A and C returns C, and is False
C and A returns C, and is False
A and not C returns True, and is True
A or B returns A, and is True
B or A returns B, and is True
C or A returns A, and is True
not A or C returns C, and is False
This lets do you useful things like this:
“some_variable = user_input or default_value”
Defining Functions
We can create a function that writes the Fibonacci series to an arbitrary boundary:
The keyword def introduces a function definition. It is followed by the function name and the list of
parameters. The statements that form the body of the function start at the next line, and must be
indented.
The first statement of the function body can optionally be a string; this string literal is the function’s
documentation string, or docstring.
The return statement returns with a value from a function. return without an expression argument
returns None. Falling off the end of a function also returns None.
Default Argument Values
It is also possible to define a function with
default value for one or more arguments. This
creates a function that can be called with
fewer arguments than it is defined to allow.
For example:
Keyword Arguments
Functions can also be called using keyword
arguments of the form keyword=value. For
instance, the following function:
could be called in any of the following ways:
Practice Intermission
Try the following problems to help gauge your
understanding:
• http://codingbat.com/prob/p173401 - creating a
fuction, simple conditionals, boolean logic
• http://codingbat.com/prob/p141905 - creating a
function, simple conditionals, simple math on
variables
• http://codingbat.com/prob/p195669 - creating a
function, slightly more complex conditionals
Strings and Things
Strings in Python are created with paired single or double quotes (e.g. “This is
a string”) and very easy to work with. Multi line strings can be created by
enclosing them with three single or double quotes on each end (e.g.
“””This could span several lines“””). Once created, strings are immutable
– any ‘modifications’ to the string really just create a new string, and
return a reference to it.
The “+” and “*” operators are overloaded for strings, so you can do neat
things like:
Strings have far too many useful methods to list here. See the Python cheat
sheet for more information.
String Formatting Operations
String and Unicode objects provide formatting via
the % operator (modulo). The effect is similar to the
using sprintf() in the C language. If format requires a
single argument, values may be a single non-tuple
object. Otherwise, values must be a tuple with exactly
the number of items specified by the format string, or
a single mapping object (for example, a dictionary).
For example:
Another Short Practice Intermission
Some more problems to try:
• http://codingbat.com/prob/p115413 - Try this
one with both string formatting, and
concatenation using operators.
• http://codingbat.com/prob/p167246 - See if
you can find a string method that will make it
trivial.
Meet the List
As previously mentioned, lists are mutable,
ordered collections of objects. Any type of
object can be put in a list, and lists may
contain more than one type of object at a
time.
In much the same manner as strings, the “+”
and “*” operators are overloaded on lists.
Useful List Methods
• list.append(x) - Add an item to the end of the list.
• list.extend(L) - Extend the list by appending all the items in
the given list.
• list.insert(position, x) - Insert an item at a given position.
• list.remove(x) - Remove the first item from the list whose
value is x. It is an error if there is no such item.
• list.index(x) - Return the index in the list of the first item
whose value is x. It is an error if there is no such item.
• list.count(x) - Return the number of times x appears in the
list.
• list.sort() - Sort the items of the list, in place.
• list.reverse() - Reverse the elements of the list, in place.
List Comprehensions
List comprehensions offer an elegant, compact way to work with lists.
Specified in the form:
[do something with item for item in original list]
For example:
An optional condition can be specified for list comprehensions as well:
[do something with item for item in original list if condition]
Sequence subscripts
In Python, all sequences (including strings, which can be thought
of as sequences of characters) can be subscripted.
Subscripting is very powerful since it allows you to view a
portion of a sequence with relative constraints.
Python subscripts may either be single elements, or slices.
Subscripts are invoked using square brackets, and slices are
designated using a colon. For example:
Subscripts, continued
Subscripts can be bounded on only one end, for
instance:
Subscripts can also be negative, to indicate position
relative to the end of the sequence:
Your Final Practice Session
Take the time to work through these exercises:
• http://codingbat.com/prob/p148661 - There’s
a list method that makes this easy.
• http://codingbat.com/prob/p171011 - Trivial if
you understand subscripts.
When you have some free time, take a look at
some of the other exercises on this site.
Sets
A set object is an unordered collection of distinct
hashable objects. Common uses include membership
testing, removing duplicates from a sequence, and
computing mathematical operations such as
intersection, union, difference, and symmetric
difference.
Like other collections, sets support x in set, len(set), and
for x in set. Being an unordered collection, sets do not
record element position or order of insertion.
Accordingly, sets do not support indexing, slicing, or
other sequence-like behavior.
Useful Set Methods
•
•
•
•
•
•
•
•
•
set.isdisjoint(other) - Return True if the set has no elements in common
with other. Sets are disjoint if and only if their intersection is the empty set.
set.issubset(other) or set <= other - Test whether every element in the set is
in other.
set < other - Test whether the set is a true subset of other, that
is, set <= other and set != other.
set.issuperset(other) or set >= other - Test whether every element in other is in
the set.
set > other - Test whether the set is a true superset of other, that
is, set >= other and set != other.
set.union(other, ...) or set | other | ... - Return a new set with elements from the
set and all others.
set.intersection(other, ...) or set & other & ... - Return a new set with elements
common to the set and all others.
set.difference(other, ...) or set - other - ... - Return a new set with elements in the
set that are not in the others.
set.symmetric_difference(other) or set ^ other - Return a new set with elements
in either the set or other but not both.
Defining the Dictionary
A dictionary maps key objects to to arbitrary value objects.
– Values that are not hashable, that is, values containing lists,
dictionaries or other mutable types may not be used as keys.
– Numeric types used for keys obey the normal rules for numeric
comparison: if two numbers compare equal (such as 1 and 1.0)
then they can be used interchangeably to index the same
dictionary entry.
Useful Dictionary Methods
•
•
•
•
•
•
•
dict.get(key[, default]) - Return the value for key if key is in the dictionary, else
default. If default is not given, it defaults to None, so that this method never raises
a KeyError.
dict.items() - Return a copy of the dictionary’s list of (key, value) pairs.
dict.keys() - Return a copy of the dictionary’s list of keys.
dict.pop(key[, default]) - If key is in the dictionary, remove it and return its value,
else return default. If default is not given and key is not in the dictionary, a
KeyError is raised.
dict.popitem() - Remove and return an arbitrary (key, value) pair from the
dictionary. popitem() is useful to destructively iterate over a dictionary, as often
used in set algorithms. If the dictionary is empty, calling popitem() raises a
KeyError.
dict.update([other]) - Update the dictionary with the key/value pairs from other,
overwriting existing keys. Return None. update() accepts either another dictionary
object or an iterable of key/value pairs (as tuples or other iterables of length two).
If keyword arguments are specified, the dictionary is then updated with those
key/value pairs: d.update(red=1, blue=2).
dict.values() - Return a copy of the dictionary’s list of values.
Basic I/O
File objects can be created with the built-in
open() function. File objects are also returned
by some other built-in functions and methods.
– Temporary files can be created using the tempfile
module
– high-level file operations such as copying, moving,
and deleting files and directories can be achieved
with the shutil module.
Modules and Namespaces
When first writing programs in Python, it is likely that all your
code will go in a single file. As your program gets longer,
you may want to split it into several files for easier
maintenance. You may also want to use a handy function
that you’ve written in several programs without copying its
definition into each program.
– To support this, Python has a way to put definitions in a file and
use them in a script or in an interactive instance of the
interpreter. Such a file is called a module. Modules can
be imported into other modules or into the main module.
– A module is a file containing Python definitions and statements.
The file name is the module name with the suffix .py appended.
Within a module, the module’s name (as a string) is available as
the value of the global variable __name__.
Some Useful Modules
• os – operating system specific functionality.
• os.path – useful tools to navigate directory strutures, work
with filenames and so forth.
• shutil – like os.path, but higher level and more powerful.
• re – Python’s regular expression module. Regular
expression is a powerful (but cryptic) text parsing language.
• math – lots of common mathematical operations.
• itertools – lots of tools for replacing clunky nested for loops
or other complex looping logic typically needed into other
programming languages.
• datetime – lots of tools for working with dates and times
(surprise!)