📚 The CoCalc Library - books, templates and other resources
License: OTHER
Math 157: Intro to Mathematical Software
UC San Diego, winter 2018
January 12, 2018: Introduction to Python (part 1 of 3)
Reminder: no class on Monday, January 15 (holiday). Discussion sections meet as usual on Tuesday.
Python is a high-level programming language used throughout the computing world for a variety of tasks, including scientific computation. Its design includes various features meant to improve readability of code, making it ideal for newcomers to programming.
The home page of the Python project is http://www.python.org; there you can find a wealth of documentation about the language and its usage. Note that there are two major forms of the language in common circulation: 'Python 2' and 'Python 3'. The differences are subtle and generally not appear in any of the presented examples; I'll only comment on them occasionally.
In today's lecture, we will focus on:
Hello World (and beyond)
Flow control:
for
,if
,while
. Whitespace matters!Functions
Remember, you can (and should) experiment with your copy of the file without disturbing anyone else.
Hello World (and beyond)
In the context of a programming language, "Hello World" refers to the simplest possible program which outputs "Hello World" (and does nothing else). In Python, "Hello World" is particularly simple.
Side note: in Python 2 one can also do print "Hello World"
without the parentheses. But doing it this way works in both Python 2 and Python 3.
Let's soup this up a bit. In Python, sequences of commands do not require any separating punctuation, just a line break. A sequence of (one or more) statements will hereafter be called a block.
As we've seen last time, you may use a single equals sign (=) to assign a value to a variable. Unlike in some other languages, there is no notion of "declaring" a variable before you use it in Python (it is a "dynamically typed" rather than a "statically typed" language).
Variables can hold different types of values. Different operations behave differently depending on the type of value involves (that is, Python exhibits "polymorphy" and "operator overloading").
Flow control
Most interesting programs do something more complicated than simply execute a list of instructions in order. The process by which a program skips or repeats code is called flow control.
Among programming languages, Python is highly unusual in that whitespace matters: it uses indentation levels to perform flow control. This design choice was made to enforce a degree of readability.
Let's see how this works with the most basic example of flow control: the if/else
statement, which performs one block if a certain binary condition is True, and another block if it is False. (The False option, indicated by else
, is optional; if omitted, it is treated as a no-op.)
File "<ipython-input-13-f72646b2d89e>", line 5
else:
^
SyntaxError: invalid syntax
Although Python is slightly more permissive than this, CoCalc enforces the convention that every indentation consists of four spaces. Note that the editor tries to help you out with this: hitting Tab always inserts four spaces, and when you start a line the editor tries to guess what indentation level you want (but of course it won't always be right).
The true/false condition can be built out of such ingredients as:
comparison (<, >, ==, !=; remember that = is assignment, == is comparison)
boolean operators (or, and, not)
parentheses (to control the order of operations).
To condition over a larger (fixed) number of options, one option would be to use a nested sequence of if/else
statements. Since this comes up a lot, Python provides a handy contraction for this: the elif
statement is like an else
plus an if
, except it saves one level of indentation.
Try this now:
Assume that the variable x
holds an integer. Write code that prints 'positive' if the integer is greater than 0, 'negative' if the integer is less than zero, or 'zero' if the integer is equal to zero.
Try this now:
Using if/else
, write a code block that prints "A", "B", "C", or "D" depending on whether the value of the variable x
reduces to 0, 1, 2, or 3 modulo 4. The operator %
performs modular division. (There are better ways to do this...)
For loops
The simplest way to repeat an operation is the for
statement, which involves setting one variable (the counter) to a succession of different values. There are several ways to specify the values, but more on that in a moment.
As you may have guessed, the start value is assumed to be 0 if not specified; the step length is assumed to be 1 if not specified; and the last value is never included.
The variable x
gets modified in the above examples...
... which can be a source of errors if you use the same variable for something else. A good way to avoid such errors is to use the Python convention that the variable _
(a single underscore) is used for such 'throwaway' uses as a counter in a for loop, and never for any 'substantive' purpose.
The content of a for
loop can be any block, which may include additional flow control.
A special command that works inside a for
loop is break
, which skips to the end of the for
loop without finishing. (Note that break
only breaks out of one such loop, in case there are nested loops.)
For more sophisticated iteration, use the while
statement, which repeats a block as long as some binary condition remains True. Again, within the block, break
terminates the loop immediately.
Try this now:
Using while
, write a loop to print all the Fibonacci numbers up to 200.
Functions (carried over to next lecture)
Functions are batches of code that can be called from within other code.
A function takes zero or more parameters, and produces zero or more return values. A function may also have side effects, although it cannot change the values of variables outside of the function (that is, variables inside a function are locally scoped).
Just like assignments of variables, the definition of a function persists between cells, unless you overwrite it by assigning the same name to another function. (If you really want, you can also type del f
which removes the definition of f
without replacing it. This works for both variables and functions; in fact, a function is just a special type of value you can assign to a variable.)
Try this now: write a function that takes four parameters and returns their average. Try the test cases below to see if your function is working.
Try this now:
Use a while
loop to write a function largest_power_of_2
that takes as input a positive integer n
and returns the largest power of 2 that is less than n
. Your loop should start with pow=1
and while pow*2
is less than n
replaces pow
with pow*2
; once the loop ends, return pow
.
Preview: data structures (not used)
Next time, we will discuss the various ways that complex data structures can be recorded in a single variable. This includes lists, which play the role of arrays...
... and dictionaries (dicts), which play the role of lookup tables (or if you like, functions defined by value tables).