Download Programming in Python

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Programming in Python
2. Numbers, Variables, Functions and Conditions
Erez Karpas (adapted from Malte Helmert)
15.10.2009
Erez Karpas (adapted from Malte Helmert)
Programming in Python
Numbers
Python knows four1 different datatypes (or classes2 ) for numbers:3
I
int for integers (whole numbers) in the range
−2147483648..2147483647 (more than that on 64 bit machines).
int corresponds to the datatype by the same name in C and Java.
I
long for integers of arbitrary size.
I
float for floating point numbers (corresponds to double in C and
Java).
I
complex for complex (floating point) numbers.
1 Actually five; starting with version 2.4, there also is Decimal for financial
applications.
2 There is a difference between datatypes and classes in Python, but it is less
important than e. g. in Java. This is an advanced topic, and for the purposes of this
course, we can pretend there is no difference.
3 Since the many footnotes are detracting, I’ll reserve the right to simplify a few
matters a bit in the following. . .
Erez Karpas (adapted from Malte Helmert)
Programming in Python
Calculating with int and long
Python mostly uses the same notation as C and Java for arithmetic:
I
Basic arithmetics: +, -, *, /
I
Modulo: %, //
I
Raising to powers (not in C/Java): **
I
Boolean bit operations: &, |, ^, ∼
I
Bit shift: <<, >>
Erez Karpas (adapted from Malte Helmert)
Programming in Python
Variables, Functions and Conditions
So far, we haven’t really gone beyond the capabilities of a calculator. To
change this, we need variables and functions. In this lesson, we cover:
I
Variables
I
Functions: def, return
I
Conditions: if, while, bool
Erez Karpas (adapted from Malte Helmert)
Programming in Python
Variables, Functions and Conditions
So far, we haven’t really gone beyond the capabilities of a calculator. To
change this, we need variables and functions. In this lesson, we cover:
I
Variables
I
Functions: def, return
I
Conditions: if, while, bool
Erez Karpas (adapted from Malte Helmert)
Programming in Python
Variables
I
Variables and assignments don’t look too surprising in Python:
Python Interpreter
>>> spam = 111 * 111
>>> spam
12321
>>> egg = spam * spam
>>> egg
151807041
>>> spam = egg * egg
>>> spam
23045377697175681L
Erez Karpas (adapted from Malte Helmert)
Programming in Python
Variables: Details
I
Variable names follow the same rules as in C:
They must consist of letters, underscores and digits. The first
symbol may not be a digit. Case is important, so spam, Spam and
SPAM are three different variable names.
I
Variables need not be declared. They come into existence as soon as
they are assigned a value. Variables cannot be used before they have
been assigned a value:
Python Interpreter
>>> spam = 3
>>> print spam
3
>>> print 10 + egg
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name ’egg’ is not defined
Erez Karpas (adapted from Malte Helmert)
Programming in Python
Variables: Type Checking (1)
I
Python is a strongly typed language, but unlike languages like C and
Java, types are not associated with variables, but with expressions.
This means that the same variable can be assigned values of
different types over time:
Python Interpreter
>>> spam = 1+7j
>>> print spam
(1+7j)
>>> spam = 100L
>>> print spam
100
>>> spam = "spam, spam, spam, spam"
>>> print spam
spam, spam, spam, spam
Erez Karpas (adapted from Malte Helmert)
Programming in Python
Variables: Type Checking (2)
I
Expressions are typed, and type errors are recognized:
Python Interpreter
>>> print "one" + 1
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: cannot concatenate ’str’ and ’int’ objects
>>> print 1j < 4
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: cannot compare complex numbers using <, <=, >,
>=
>>> print "Gambolputty"[2.0]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: string indices must be integers
Erez Karpas (adapted from Malte Helmert)
Programming in Python
Variables: Tuple Unpacking
I
It is possible to assign several values at the same time:
Python Interpreter
>>> spam, egg = 7, 13
>>> print spam
7
>>> print egg
13
I
This is called “tuple unpacking” – more on tuples later.
Erez Karpas (adapted from Malte Helmert)
Programming in Python
Variables, Functions and Conditions
So far, we haven’t really gone beyond the capabilities of a calculator. To
change this, we need variables and functions. In this lesson, we cover:
I
Variables
I
Functions: def, return
I
Conditions: if, while, bool
Erez Karpas (adapted from Malte Helmert)
Programming in Python
Functions
To be able to write real programs, we need functions. Here we see one of
Python’s specialties:
Python Interpreter
>>> def triple(egg):
...
return 3 * egg
...
>>> print triple(10)
30
>>> def double(spam):
... return 2 * spam
File "<stdin>", line 2
return 2 * spam
^
IndentationError: expected an indented block
Erez Karpas (adapted from Malte Helmert)
Programming in Python
Indent!
I
In Python, the block structure of a program is marked by
indentation, not by parentheses or keywords as in other languages.
I
The basic rule is simple: Everything that belongs to the body of the
function must be indented with respect to the definition of the
function.
I
In other words: Just indent the same way you would in a
conventional programming language like C or Java (following the
style guides for that language).
This feature is so characteristic for Python that there are T-Shirts with
the slogan:
Python — Programming the way Guido indented it.
Erez Karpas (adapted from Malte Helmert)
Programming in Python
Careful: Tabs and Spaces
I
Python understands both spaces and tab characters as indentation
markers.
I
As long as the two aren’t mixed, there are no problems.
I
If they are mixed (bad! bad!), it is important that the editor used for
the Python program follows the UNIX standard (tab stops at
positions 1, 9, 17, . . . ).
I
It is best to avoid tab characters in Python programs altogether by
setting the editor to only write spaces upon saving a file.
I
When invoked with the option -t, Python warns when it encounters
“dangerous” files.
Erez Karpas (adapted from Malte Helmert)
Programming in Python
While We Are Discussing Formatting. . .
I
You might have noticed that the end of a statement is also
determined by formatting in Python.
I
More precisely: The statement ends with the end of line (there is no
need for terminating statements with ; as in C-like languages).
I
Sometimes we don’t want that:
a_long_name = another_long_name +
an_even_much_much_longer_name
This leads to an error after processing the first line.
Erez Karpas (adapted from Malte Helmert)
Programming in Python
Long Lines
There are two ways of splitting statements across lines:
I
If a line ends with a backslash, it is joined with the following line (as
in C).
a_long_name = another_long_name + \
an_even_much_much_longer_name
I
If closing parentheses, brackets or braces are pending, the end of line
does not terminate the statement:
a_long_name = (another_long_name +
an_even_much_much_longer_name)
This leads to an error after processing the first line.
It is considered good style to use the second way of splitting lines in favor
of the first, introducing additional parentheses when necessary.
Erez Karpas (adapted from Malte Helmert)
Programming in Python
Back to Functions
Python Interpreter
>>> def triple(egg):
...
return 3 * egg
...
>>> print triple(10)
30
>>> def double(spam):
...
return 2 * spam
...
>>> print double(5.5)
11.0
Erez Karpas (adapted from Malte Helmert)
Programming in Python
Functions: Details
I
Functions are introduced with the keyword def.
I
Functions may accept a variable number of arguments, and default
arguments are supported – more on this later.
I
The result of a function is specified with the keyword return, which
also terminates execution of the function.
Functions always return a result.
I
I
I
If a function does not use an explicit return statement, the special
value None is returned, which is an (actually, the only) instance of
class NoneType.
None is Python’s equivalent of NULL in C/C++,
null in Java, nil in LISP, and void in C, C++ and Java.
Erez Karpas (adapted from Malte Helmert)
Programming in Python
Functions: Examples
Python Interpreter
>>> def product(x, y, z):
...
return x * y * z
...
>>> print product(5, 6, 7)
210
>>> def sing():
...
print "spam, spam, spam, spam"
...
>>> sing()
spam, spam, spam, spam
>>> print sing()
spam, spam, spam, spam
None
Erez Karpas (adapted from Malte Helmert)
Programming in Python
Functions: Polymorphism (1)
I
Python functions are polymorphic, which means that they can deal
with variables of different types as long as those types support all
necessary operations:
Python Interpreter
>>> def double(anything):
...
return 2 * anything
...
>>> print double(10.2)
20.4
>>> print double("badger")
badgerbadger
Erez Karpas (adapted from Malte Helmert)
Programming in Python
Functions: Polymorphism (2)
I
Type errors are detected at runtime:
Python Interpreter
>>> def double(anything):
...
return 2 * anything
...
>>> print double(None)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 1, in double
TypeError: unsupported operand type(s) for *: ’int’ and
’NoneType’
I
More on Python’s polymorphism under the topic duck typing.
Erez Karpas (adapted from Malte Helmert)
Programming in Python
Functions with Multiple Results
I
Functions can have multiple results.
I
An example of this is the built-in function divmod:
Python Interpreter
>>> print divmod(20, 6)
(3, 2)
I
We can use tuple unpacking as seen earlier to assign variables to
both results:
Python Interpreter
>>> x, y = divmod(20, 6)
>>> print x
3
>>> print y
2
I
More on this when we will discuss tuples.
Erez Karpas (adapted from Malte Helmert)
Programming in Python
Built-in Functions (“builtins”)
I
I
Similar to Java, most of Python’s functions are stored in packages
and modules, and must be imported from those before they can be
used.
Some commonly used functions need not be imported – the
so-called builtins.
Some important builtins:
I abs(x)
I
I
I
divmod(x, y)
I
I
I
I
I
x // y and x % y (returns two results).
min(x, y, ...), max(x, y, ...)
I
I
Absolute value of number x.
Also works for complex numbers.
Minimum or maximum of the arguments.
Variable number of arguments (at least 1).
pow(x, y[, z])
With two arguments: Computes x ** y.
With three arguments: Computes (x ** y) % z.
Erez Karpas (adapted from Malte Helmert)
Programming in Python
Variables, Functions and Conditions
So far, we haven’t really gone beyond the capabilities of a calculator. To
change this, we need variables and functions. In this lesson, we cover:
I
Variables
I
Functions: def, return
I
Conditions: if, while, bool
Erez Karpas (adapted from Malte Helmert)
Programming in Python
Checking Conditions with if and else
Python Interpreter
>>> def factorial(n):
...
if n <= 1:
...
return 1
...
else:
...
return n * factorial(n - 1)
...
>>> print factorial(10)
3628800
I
Should be self-explanatory. . .
Erez Karpas (adapted from Malte Helmert)
Programming in Python
More on if and else
I
In addition to if and else, there are else-if blocks, which are
written as elif in Python. The general form looks like:
if <bedingung>:
<Code>
elif <bedingung>:
<Code>
elif <bedingung>:
<Code>
...
else:
<Code>
I
The elif parts and else part are optional.
Erez Karpas (adapted from Malte Helmert)
Programming in Python
while Loops
Python Interpreter
>>> def factorial(n):
...
result = 1
...
i = 2
...
while i <= n:
...
result = result * i
...
i = i + 1
...
return result
...
>>> print factorial(10)
3628800
I
Should be self-explanatory. . .
I
while loops are quite rare in Python, as for (later) usually is the
better alternative.
Erez Karpas (adapted from Malte Helmert)
Programming in Python
More on Conditions
I
For conditions, the usual comparison operators from C/C++ and
Java can be used:
I
I
==, !=: Equality and inequality (<> is a rarely used synonym for !=).
<, <=, >, >=: Checking order
I
Conditions can be connected using and, or and not (not &&, ||, !).
I
Comparisons can be chained as in mathematics:
0 <= x <= 10 is thus equivalent to (0 <= x) and (x <= 10).
Erez Karpas (adapted from Malte Helmert)
Programming in Python
Example for and, or and not
Python Interpreter
>>> def is probably prime(n):
...
if n == 2:
...
return True
...
elif n <= 1 or n % 2 == 0:
...
return False
...
elif n <= 20 and not (n == 9 or n == 15):
...
return True
...
else:
...
return n % 3 != 0 and n % 5 != 0
Erez Karpas (adapted from Malte Helmert)
Programming in Python
Conditions: The bool Type
I
Comparisons may be used outside of if and while statements:
Python Interpreter
>>> print 1 + 1 == 2
True
>>> condition = 24 < 6 * 6 < 26
>>> condition
False
I
The result of a comparison is either the constant False or the
constant True.
I
The type of those constants is bool.
Erez Karpas (adapted from Malte Helmert)
Programming in Python