E19 Lab 0 Guide

The goal of this lab assignment is to get you started with basic coding skills in Python.

Python Workflow

Once you have Python installed on your system, there are a few different ways of using it. None of these is the 'right' way to code in Python; feel free to try out multiple approaches and see which one works best.

  1. 'Integrated Development Environments' or IDEs'

    An IDE is a program that 'integrates' your coding workflow by combining an intelligent text editor (with line numbers, neat indentation, and syntax highlighting) with a runtime environment. Because you can write and run code in the same place, it's a good idea to use an IDE for debugging. Two examples of IDEs that are good for Python are VS Code and Spyder.

  2. 'IDLE': Integrated Development and Learning Environment

    IDLE comes bundled with Python, and is a great environment to start coding in Python with. When you run IDLE, you will get a command line interface waiting for you to type code in. If you write a line of code and hit enter, IDLE with execute the line and, if there was any output associated with it, you will see the output on the next line. Inside the 'IDLE' command line interface, it's best to write lines one at a time, but if you have a 'for loop' or other block of code, you can keep typing until the block is complete. IDLE also gives you a text editor specifically for Python files. Just go to File > New File and you will get a notepad-like interface to write code in, complete with syntax highlighting and indentation. Save your code as a *.py file, and then you can hit Run on the toolbar to execute the file altogether.

  3. Python interpreter in the Terminal (Mac) or Command Prompt (Windows).

    This is what will open up if you type 'python' or 'python3' into the Command Prompt or Terminal. It's a Python interpreter, just like IDLE, but within the 'shell' of the Terminal or the Command Prompt

  4. Executing Python files from the terminal/command prompt.

    If you write Python code in a text file (the convention is to use *.py extensions) and then type 'python <filename>' or 'python3 <filename>' from the terminal or command prompt, the file will execute and any output (such as 'print' statements) will print to the terminal/command prompt.

No matter which of these workflows you choose, it is important to always be aware of which environment you are in -- https://nextjournal.com/emad-masroor-teaching/e19-python-environments

Coding in Python

Assigning a variable

The very first thing you will likely do when programming, is assign a value to a variable. In Python, you do this with a simple '=' symbol:

a = 5
0.1s
Conditionals

Next, you may want the computer to check a mathematical statement. In Python, you do this using Boolean operators, which return either 'True' or 'False'.

[a < 2,
 a != 7,
 a == 2.9,
 a > 3,
 a >= 4,
 a <= 3]
0.1s
Lists

In the previous block of code, we created a 'list'. A list is simply a collection of objects, and in Python it is created using square brackets and commas to separate each element. The elements do not need to be on a new line.

b = [2,3,6]
0.0s
Types

Variables in Python have a 'type' associated with them. Some common types include

  • int, integer

  • float, floating-point number -- in practice, this type is used for real numbers.

  • str, string -- used for text

If statements

'If' statements are one of the most powerful tools in a programmer's toolbox. They work by providing the computer with a conditional statement that is either true or false. The program does something different depending on whether the statement was found to be true or false.

c = 3
if c > 4:
  print('c is greater than 4')
else:
  print('c is not greater than 4')
0.3s

You can even have multiple 'else' statements, which are checked sequentially, using the 'elif' keyword (which stands for 'else, if').

d = 4
if d > 3:
  print('d is greater than 3')
elif d > 2:
  print('d is greater than 2')
else:
  print('Not sure')
0.3s

Why did 'd is greater than 2' not get printed, when d is, in fact, greater than 2?

For and while Loops

You will most commonly encounter two types of 'loops': for loops and while loops.

For loops run some code for a specific number of times.

for i in [1,2,5]:
  print(i)
0.3s

There are many options for what you put after 'in'; technically, anything that can be put there is called an iterable. A list is an iterable, but so is a 'range' or a numpy array.

for something in range(5):
  print(something)
0.3s

A while loop runs while a certain condition holds true. If that condition is always true, your while loop will literally run for ever. So it's a good idea to use while loops after you have an idea for when you want your loop to stop.

k = 0
while k < 8:
  k += 1
  print('The value of k is',k)
0.4s

You can also add a 'break' statement. For example:

k = 0
while 2+2==4:
  k += 1
  print('Loop is still looping, k = ',k)
  if k > 8:
    break
    
0.4s

Arithmetic

Python supports the following arithmetic operations: add (+), subtract (-), multiply (*), divide (/), raise to the power (**), and two other operations with which you may not be as familiar: integer quotient (//) and remainder or modulo (%). These are illustrated below:

[2+2,
 3-2,
 3*2,
 5/2,
 9**2,
 14//3,
 14%3]
0.0s

Plotting

In Python, the ability to make plots does not come built-in. In this class, we will mostly use the 'matplotlib' package for plotting.

This is a gigantic package with lots of different options for customizing your plotting experience. You can visit their website here: https://matplotlib.org/. Matplotlib has a module called 'pyplot'.

Here is a simple working example of how to make a plot using matplotlib. The general idea is : assemble a set of numbers containing the x-locations of the points you want to plot, a set of numbers containing the y-locations, and then pass the two sets to the function 'plot'.

import numpy as np
import matplotlib.pyplot as plt
a = np.linspace(0,2*np.pi,200)
b = np.sin(a)
plt.plot(a,b)
0.3s

You can customize your plot by looking through the documentation on https://matplotlib.org/.

Printing to a text file

To print to a text file, your code will have to 'open' a file, 'write' in it, and then 'close' it.

f1 = open('/results/test_file.txt','w') # 'w' indicates 'write mode', as opposed to read-only
f1.write(f'some text \nsome more text') # writes some text. '\n' creates a new line.
f1.close() # closes the file
0.0s
f2 = open('/results/numbers.txt','w')
for i in range(10):
  # print the variable i, converted into a string using 'str(i)', concatenated with the new line symbol '\n'.
  f2.write(str(i)+'\n') 
f2.close()
0.0s

Some features of Python

Indentation

Python is an 'indented' language. This means that the indentation of your code matters, unlike some other languages where this is not the case. Thus, the following code will run into an error.

a = 5
 b = a +1
0.0s

When you use loops or if statements, you have to keep track of indentation, and 'go back to' the previous level of indentation if you want your code to be outside the 'block' created by an if, for, or while statement.

k = 0
while True:
  a = 0
  k += 1
  print('k = ',k)
  if k == 5:
    print('k is now equal to 5')
  elif k > 5 and k < 10: # two different conditions
    print('k is between 5 and 10')
    if k == 8:
      print('k is equal to 8')
  if k > 10:
    break
    
0.3s
odu
Runtimes (1)