Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132928 views
License: OTHER
Kernel: Python 3 (Ubuntu Linux)

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:

  1. Hello World (and beyond)

  2. Flow control: for, if, while. Whitespace matters!

  3. 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.

print("Hello World")
Hello World

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.

print("Hello World") # Any text after a hash mark is a comment, ignored by Python # Comments are useful for pointing things out to the reader. For instance, the previous blank line is ignored. print("Hello again")
Hello World Hello again

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).

x = 5 y = 7 print(x+y)
12
this_is_a_long_variable_name_744 = 2

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").

x = "5" # Replaces the previous value y = str(7) # Convert this integer to a string print(x+y) # This is a string, not an integer
57

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.)

# Compare this example... x = 3 y = 5 if x < y: # Note that = means assignment; == means test for equality. print(x,y) # By the way, print can take a comma-separated sequence of arguments. else: print(y) print(x)
3 5
# ... with this one. x = 3 y = 5 if x < y: print(x,y) else: print(y) print(x) # Removed indentation on this line; it's not part of the conditional statement
3 5 3
x = 3 y = 5 if x < y: print(x,y) else: print(y) print(x)
File "<ipython-input-13-f72646b2d89e>", line 5 else: ^ SyntaxError: invalid syntax
if not (x == y): print(x,y)
3 5

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).

# use the same x, y as before if (x<4 and y>4) and not (x+y==9): print(x,y)

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.

if x == 5: print("yes") else: if x == 3: print("better") if y == 3: print("y = 3") else: if (y == 2 and x > 7) or x < 3: print("??") else: print("best")
if x == 5: print("yes") elif x == 3: print("better") if y == 3: print("y = 3") elif (y == 2 and x > 7) or x < 3: print("??") else: print("best")

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.

# Your code goes here... if x>0: print("positive") elif x<0: print("negative") else: print("zero")
positive

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...)

27%5 # Modular division
2
# Your code goes here... if x%4 == 0: print("A") elif x%4 == 1: print("B") elif x%4 == 2: print("C") else: print("D")
D

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.

for x in range(5): # Note carefully what values are generated! print(x)
0 1 2 3 4
for x in range(3, 7): # Here we specify the start and end of the range. print(x)
3 4 5 6
for x in range(1,11,2): # Here we specify the start value, end value, and step length. print(x)
1 3 5 7 9

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...

x
9

... 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.

for _ in range(3): print("ahooga")
ahooga ahooga ahooga

The content of a for loop can be any block, which may include additional flow control.

for x in range(3): for y in range(4): print(x,y) print(x + y)
0 0 0 0 1 1 0 2 2 0 3 3 1 0 1 1 1 2 1 2 3 1 3 4 2 0 2 2 1 3 2 2 4 2 3 5

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 x in range (3): for y in range(4): print (x,y) if x+y > 2: break
0 0 0 1 0 2 0 3 1 0 1 1 1 2 2 0 2 1

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.

x = 0 y = 0 while (y < 100): x += 1 # Has the same effect as x = x + 1 y += x print(y)
1 3 6 10 15 21 28 36 45 55 66 78 91 105

Try this now:

Using while, write a loop to print all the Fibonacci numbers up to 200.

# Your code goes here... x = 0 y = 1 while (y <= 200): print(y) x,y = y, y+x
1 1 2 3 5 8 13 21 34 55 89 144

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.)

def name_of_function(argument1, argument2): print("the first argument is ", argument1, " and the second is ", argument2) return argument1 + argument2
# Let's see if that worked! name_of_function("foo", "bar")
output = name_of_function(15, 19) # This doesn't print the return value, but there is a side effect
print(output) # Now let's see the return value
name_of_function('abc', 123) # This will fail -- you can't add a string and a number in Python

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.

def avg(x1, x2, x3, x4): # your code goes here...
avg(1,3,5,7) # Should return 4
avg(1,2,3,4) # What do you expect to see here? Are you surprised?

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.

def largest_power_of_2(n): #insert code here
# Test this out! for x in range(1, 17): print(x, largest_power_of_2(x))

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...

[i^2 for i in range(5)]
[2,3,5] + ["foo", "bar"]

... and dictionaries (dicts), which play the role of lookup tables (or if you like, functions defined by value tables).

d = {2:5, 3:7, 4:-1} d[2] + d[4]