Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download
Views: 16658
%md # Math 152: Intro to Mathematical Software ### 2017-01-11 ### Kiran Kedlaya; University of California, San Diego ### adapted from lectures by William Stein, University of Washington ## **Lecture 3: The Python Language (part 1)** ### Guest lecturer: Alyson Deines (Center for Communications Research)

Math 152: Intro to Mathematical Software

2017-01-11

Kiran Kedlaya; University of California, San Diego

adapted from lectures by William Stein, University of Washington

Lecture 3: The Python Language (part 1)

Guest lecturer: Alyson Deines (Center for Communications Research)

%md Administrivia: - No class Monday, January 16 (university holiday: Martin Luther King, Jr. Day). Also no sections or office hours that day. - No instructor office hours on Tuesday, January 17. - Homework 1 due Tuesday, January 17 at 8pm. Remember, put all your work in the "assignments/2017-01-17" folder; it will be collected automatically after the deadline passes. - Guest lecturer Friday, January 20: William Stein, the creator of SageMath and SageMathCloud.

Administrivia:

  • No class Monday, January 16 (university holiday: Martin Luther King, Jr. Day). Also no sections or office hours that day.

  • No instructor office hours on Tuesday, January 17.

  • Homework 1 due Tuesday, January 17 at 8pm. Remember, put all your work in the "assignments/2017-01-17" folder; it will be collected automatically after the deadline passes.

  • Guest lecturer Friday, January 20: William Stein, the creator of SageMath and SageMathCloud.

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. From 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". Since Sage is built on Python 2, we will focus on that; however, the distinctions are mostly subtle and we generally won't run into them in our examples.

In today's lecture, we will focus on:

  1. Hello World (and beyond)

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

  3. Functions

As usual, please follow along and experiment in your copy of this file!

Hello World

%md Every time you evaluate a cell in SMC, you are running a Python program (unless the cell is marked as a different language, like md as these narrative cells.) In particular, the following is a complete Python program!

Every time you evaluate a cell in SMC, you are running a Python program (unless the cell is marked as a different language, like md as these narrative cells.) In particular, the following is a complete Python program!

Type stuff

print("Hello World")
Hello World
print "Hello World"

One can of course string together commands to make a more interesting program. Note that no punctuation is required at the end of a line.

# Any line starting with # is a comment; the rest of the line is ignored. # Use comments to document your code for improved readability! print("Hello World") # Comments can also occur after a valid statement # Blank lines are permitted, are ignored print("Hello again")
Hello World Hello again
# Use a single = sign to assign a value to a variable. No need to declare the variable beforehand! x = 3 y = 5 print(x+y)
# Variables retain their value between cells. print(x/y)
3/5
# Variables can hold different types of values, which behave differently under operations. x = "3" # Replaces the previous value y = "5" print(x+y) # This is a string, not an integer
35

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 unusual in that whitespace matters: it uses indentation levels to perform flow control. This design choice was made to enforce a degree of readability.

# Compare this example... x = 3 y = 5 if x == y: print x print y else: print y print x
3 5
# ... with this one. x = 3 y = 5 if x < y: print x print 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 == 5: print "yes" elif x == 3: print "better" if y == 3: print "y = 3" elif (y == 2 and x > 7) or x < 3: priint "??"

The previous example demonstrates the if statement. (The else part is optional.)

The true/false condition can be built out of such ingredients as:

  • comparison (<, >, ==; note that a single = is assignment, not comparison)

  • boolean operators (or, and, not)

  • parentheses (to control the order of operations).

Try some examples below!

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(1,11,2): # You can also specify the starting value, ending value, and step length. print(x)
1 3 5 7 9

You can put any valid code inside a for block, including additional flow control.

for x in range(3): for y in range(4): print(x,y) #This is a tuple, more on this shortly print( x + y)
(0, 0) (0, 1) (0, 2) (0, 3) (1, 0) (1, 1) (1, 2) (1, 3) (2, 0) (2, 1) (2, 2) (2, 3)

For more sophisticated iteration, use the while statement. It keeps repeating the block as long as a true/false condition remains true. (Within the block, ` 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

Functions

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

Definitions of functions persist between cells.

def name_of_function(argument1, argument2): # This is a function. I changed print "the first argument is ", argument1, " and the second is ", argument2 return argument1 + argument2
output = name_of_function(15, 19) # This doesn't print the return value, but there is a side effect
the first argument is 15 and the second is 19
print(output)
34
name_of_function('math', '480') # The types of the parameters may vary between calls
the first argument is math and the second is 480 'math480'
name_of_function('abc', 123) # This will fail -- you can't add a string and a number in Python
the first argument is abc and the second is 123
Error in lines 1-1 Traceback (most recent call last): File "/projects/sage/sage-7.3/local/lib/python2.7/site-packages/smc_sagews/sage_server.py", line 976, in execute exec compile(block+'\n', '', 'single') in namespace, locals File "", line 1, in <module> File "", line 3, in name_of_function File "sage/rings/integer.pyx", line 1592, in sage.rings.integer.Integer.__add__ (/projects/sage/sage-7.3/src/build/cythonized/sage/rings/integer.c:10979) return coercion_model.bin_op(left, right, operator.add) File "sage/structure/coerce.pyx", line 1091, in sage.structure.coerce.CoercionModel_cache_maps.bin_op (/projects/sage/sage-7.3/src/build/cythonized/sage/structure/coerce.c:9974) raise TypeError(arith_error_message(x,y,op)) TypeError: unsupported operand parent(s) for '+': '<type 'str'>' and 'Integer Ring'

Try this now: write a function that takes four parameters and returns their average.

def avg(x1, x2, x3, x4): # write code here return (x1 + x2 + x3 + x4)/4
#Test cases here avg(1,2,3,4)

Try this now: Write a function that takes a number and returns "positive" if the number is greater than 0, "negative" if the number is less than zero, or "zero" if the number is equal to zero. Hint: the statement elif is equivalent to else if.

def my_sign(n): # write your code here if n > 0: return "positive" elif n == 0: return "zero" elif n < 0: return "negative"

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 pow = 1 while pow*2 < n: pow *= 2 return pow
lst = [i for i in range(10)]
lst
[0, 1, 2, 3, 4, 5, 6, 7, 7, 9]
lst1 = [1, 3, 4, 1, 5]
unknown message type '6one'
lst + lst1
[0, 1, 8, 3, 4, 5, 6, 7, 8, 9, 1, 3, 4, 1, 5]
lst2 = [1, 3, "abc"]
lst2
[1, 3, 'abc']
def ave_better(lst): length = len(lst) list_sum = sum(lst) return list_sum/length
lst
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
ave_better(lst)
9
ave_better(lst1)
14/5
lst0 = [] for i in range(10): lst0.append(i)
lst0
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
lst = [i for i in range(20) if i % 2 == 0] print lst
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
lst = [i for i in range(0, 20, 2)]
lst
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
D = {} for i in range(10): D[i] = 2*i
D
{0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}
D[3]
6
lst
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
lst[3]
6
D = {i: 2*i for i in range(10)}
D
{0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}
%md %hide Type stuff

%hide Type stuff

︠be854037-6936-4c41-ba13-33ad4a5d5860︠ ︠5a4d2b03-9aac-47b4-8157-99da23a8b761︠