pm21-dragon/lectures/lecture-03/1 - flow control.ipynb
Andrew Straw a1d4f6d002 lecture 3
2024-11-04 13:51:43 +01:00

88 KiB
Executable file

None <html> <head> </head>

Reminder: Do not rename file (or allow your computer to do that)

Please overwrite the original exercise release file(s) when uploading your assignment. I still had to fix some of your submissions.

Update: Trouble with previous assignment due to _ breaking.

In the previous assignment, some of you had trouble because the assignment expected _ to be the output of the previous cell, but the Jupyter output was increasing by "2" as described here. The solution to this problem is to disable the Anaconda Assistant, namely:

Steps to fix:

  1. Disable Anaconda Assistant
  2. Run jupyter labextension disable @anaconda/assistant
  3. Restart the Jupyter notebook

() and []

Remember that Python is very, very precise about how it understands your code.

() have multiple meanings in python:

  • function call: my_function(arg1)
  • defining a function: def my_function(arg1):
  • specifying the order of operations: 4*(3+2)
  • creating a tuple: (1,2,3,4) or (1,) or () (Note that (1) will not create a tuple. Also: you can create a tuple without parentheses...)

[] similarly has a few meanings, based on context

  • creating a list: [1,2,3,4] or [1,] or [1] or []
  • getting an item: x = my_list[index]
    • getting a slice: x = my_list[start_index:end_index:increment]
  • setting an item: my_list[index] = x

Basic plotting, revisited

In [1]:
# Below, we will use matplotlib, so we need to import it here.
import matplotlib.pyplot as plt
In [2]:
x=[1,2,3,4,5,6,7,8,9,1]
y=[0,4,0,3,3,0,3,4,5,2]
In [3]:
plt.plot(x,y,'--')
Out[3]:
[<matplotlib.lines.Line2D at 0x10b899cd0>]
In [4]:
x=[1,2,3,4,5,6,7,8,9,10]
y1=[0,4,0,3,3,0,3,4,5,2]
y2=[3,2,4,4,2,4,4,2,4,2]
plt.plot(x,y1)
plt.plot(x,y2)
Out[4]:
[<matplotlib.lines.Line2D at 0x10ba02490>]

String formatting

Old-style string formatting with %

When the operator % is used on a string, the string is used as a format string for old-style formatting.

In these old-style format strings, %d means to print an integer, %s means to print a string.

In [5]:
"The numbers are %d, %d, %d" % (5,10,20)
Out[5]:
'The numbers are 5, 10, 20'
In [6]:
tmp = (5,10,20)
"The numbers are %d, %d, %d" % tmp
Out[6]:
'The numbers are 5, 10, 20'
In [7]:
tmp = (5,10,20,100)
"The numbers are %d, %d, %d" % tmp
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[7], line 2
      1 tmp = (5,10,20,100)
----> 2 "The numbers are %d, %d, %d" % tmp

TypeError: not all arguments converted during string formatting
In [ ]:
tmp = (5,10)
"The numbers are %d, %d, %d" % tmp
In [ ]:
my_string = "The numbers are %d, %d, %d"
my_string
In [ ]:
my_string%(7, 14, 21)
In [ ]:
tuple1 = (100, 200, 300)
my_string % tuple1
In [ ]:
"The numbers are %d, %d, %d"%(5,10)
In [ ]:
"The numbers are %d, %d, %d"%(5,10,20,40)
In [ ]:
"Hello %s"%("world")
In [ ]:
"Hello %s"%1
In [ ]:
"Hello %d, %d"%(1, 2)
In [ ]:
"Hello %d, %d"%(1, 2)
In [ ]:
"Hello %d"%1
In [ ]:
"Hello %d"%'hello'
In [ ]:
"Hello %s"%'hello'

New-style (since Python 2.7) formatting with .format()

In [ ]:
"The numbers are {}, {}, {}".format(5,10,20)
In [ ]:
"Hello {}".format("world")

Even newer (since Python 3.6) style formatting with f-strings.

In [ ]:
name="Andrew"
my_string = f"Hello, my name is {name}."
print(my_string)
In [ ]:
f"Hello, my name is {name}."
In [ ]:
f"Hello, my name is {name}. {akjfhasd}"
In [ ]:
f"Hello, my name is {name}. {{akjfhasd}}"
In [ ]:
"Hello, my name is {}.".format(name)
In [ ]:
my_template = "hello {}"
print('my template is:', my_template)
my_template.format(name)
In [ ]:
my_template = "hello {}"
my_template.format(name)
print('my template is', my_template)

Control flow with while

In [ ]:
x = True
y = 0
while x:
    print(y)
    y = y + 100
    if y >= 1000:
        x = False
print('done')
In [ ]:
y = 0
while True:
    print(y)
    y = y + 100
    if y >= 1000:
        break
print('done')
In [ ]:
y = 0
while y < 1000:
    print(y)
    y = y + 100
print('done')

break and continue

In [ ]:
y = 0
while True:
    print(y)
    y = y + 100
    if y >= 1000:
        break
In [ ]:
y = 0
while True:
    print(y)    
    y = y + 100
    if y >= 1000:
        break
    if y < 400:
        continue    
    y = y + 10
In [ ]:
y

The += (and -=, *=, .. ) operator.

In [ ]:
y += 20
In [ ]:
y
In [ ]:
y = y +20
In [ ]:
y
In [ ]:
y -= 20
In [ ]:
y

Running Python from the terminal

We want to be able to run Python from the terminal. This is a low-level approach but will let us Python on all kinds of computers in all kinds of ways, not just interactively inside a Jupyter notebook.

First, we need to be able to edit Python scripts. There are lots of programs that let us do that. I recommend Visual Studio Code. To keep things simple, you can also use Jupyter Lab. In that case, you can click on the "+" in the tab list to open a Launcher tab, scroll down and create a "Python File". This will open an empty untitled.py file in the Jupyter lab editor. These .py files are plain text files which the .py extension tells the computer that this file should be Python source code. Let's create a file called hello.py which has the following contents.

print("hello world")

Now, let's run it in the terminal. Again, this can be done in multiple ways. One way is to use Jupyter Lab by clicking on the "+" in the tab list again. This type create a "Terminal". Another way is to use Anaconda Navigator as shown in this movie:

</html>