Computer programming CP-3, 2021-22; the initial parts of this writeup also are used in the second semester of computer programming CP-1A, 2021-22
Las Cruces Academy, physically in Mesilla, NM, USA
Teacher Vincent Gutschick – programmer with 58 years’ experience in Fortran, BASIC, Python, HTML, PHP, and bits of specialty languages, from a scientific career in chemistry, physics, biology, and applied fields
Python programming – a listing of topics in the course, a refresher on using Google’s Colab site, and some initial exercises to try, with guidance to the abundant tutorials available online
Python is the most popular programming language for code developers (e.g., applications on mobile devices, desktop and laptop computers, many websites) and hobbyists, and is also a useful adjunct language for scientists and engineers outside of their powerful scientific languages (Fortran, Julia, Matlab).
Python can be implemented on almost any kind of computer in the world, from tiny Raspberry Pi computers to supercomputers. It has universal standards for syntax – that is, Python code that works on a Raspberry Pi works on your Chromebook or on a supercomputer.
Python can be installed on a computer as a resident program, meaning that it runs on the computer without needing a link to the Internet, or it can be accessed readily via a programming interface (API) such as Google Colab, which is what we are doing in this course. We simply open a tab in our browser and go to the URL colab.research.google.com. We type our code in the “boxes” (windows) that we can open on the page. We can save our code in our Google Drive – that works IF we sign onto our Chromebook using our Google account (and that is NOT the same as a gmail account, please note; I have clarified this a number of times – see, for example, this file).
Python is a high-level language. It has built into it all the controls for input, output, calculation, branching, etc., so that you don’t have to figure out how to find the keyboard input or the screen for output or figure out what pixels need to be set to print a “six.” The language you may have been using earlier, Scratch, might be described as even higher level. You can move coding blocks around and Scratch will figure out which blocks are touching and are therefore linked; it also adds your coding blocks to big chunks of premade code that run the motion for a sprite. Python is then a good step deeper into programming. We won’t go into low-level languages, which go as deep as machine code that specifies basically what every register in the CPU is doing, which lines of access are open, etc. No one codes routinely in machine code, doing it only to optimize very special actions.
Working in Colab:
- When you open the page, you are in a saved space called a Jupyter notebook.
- You can have lots of code modules in the notebook – e.g., one program that presents a quiz to a user, another that creates colored areas in a plot, another that reads data on weather to figure out the highest temperature, another that draws an animation of a car or an animal moving.
- You can stay in the notebook that opens or you can:
- Create a new notebook, which is handy if you have lots of code modules and don’t want to have to scroll all over the place in one notebook – group your code by type, such as surveys in one notebook, animations in another, and so on. Click on File, then in the expanded menu on New notebook. Give the new notebook a name by clicking in the area in the top that holds the notebook name, between a Google Drive triangle and the suffix ipynb.
- Go to another notebook that you created earlier. Near the top of the page, click on File, then on Open notebook, where you choose one of your other notebooks.
- In any notebook, you can open a new module at any time, by clicking on the +Code icon. (The +Text icon is for adding notes that don’t run as a program.)
- As you type in a line of code, it gets a new number. The line numbers are for convenience; they are not part of the code.
- You’ll need to know how Python programs are structured, of course. We’ll get to that. That is, you need to know about:
- Three types of variables – strings (such as sger23hI), integers (1, 37, 875643), and floating point numbers (0.0012, 3.7, 88845.0)
- Converting strings to numbers – I’ll go over this with several examples
- Arrays – ordered lists of variables, such as arr=[0.1]*12+[5, 7, 9]
- Reading in data, either from the keyboard (as with y=input() ) or from an existing data file (as with readCSV(….)
- Printing, with print(myvariable) or print(“mystring”, 3.8)
- Control loops – if/else decisions, loops over a range of values (for loops) or during a condition (while loops), and some elaborations (except and others)
- Calling on a subroutine to do some calculations and return results
- Importing premade code modules, such as import time, numpy – these save you much work that is usually not useful to do (reinventing the wheel)
- Tests of equality or inequality, such as if x==1 or while zz>2
- Indenting of lines as rigorously enforced syntax. These lines are valid:
if time > 1.2:
x=x+2 🡨 correct amount of indenting, two spaces, that matches the rest
But these lines are invalid:
x-x+2 🡨 missing indenting for actions to occur under control of if
else 🡨 missing colon at end
x-x-1 🡨 too much indenting
There’s more to learn and it will be fun and rewarding when you create nice programs that amuse, teach, or do calculations that would take you or a collaborator way too much time by hand.
There are copious tutorials online. You can always open up a new tab in the browser and search for information. You’ll learn how to do it efficiently. Some examples:
python 3 convert string to integer – Note that capitalization is not needed, as in Python 3 vs. python 3
python datetime – for getting the date and time, or converting date and time into a single string
python matplotlib colors – find out how to get the colors you want in a plot
Here I often make it python 3, since there is an earlier version, Python 2, with different syntax
Not all searches will work the first time you try them. You may need to correct a spelling, or get more specific, or find a page that works for simple code instead of highly structured code that complies with the C language. You’ll get good at it.
A simple exercise: Enter this code that asks you to answer a question and then expand it to print different text, depending on your specific answer:
ans=input(“Do you like chocolate? “) — you can have a prompt in a request for input
# This is a comment that is not executed; use these to remember what you’re doing
# I put extra spaces after the question mark so that you answer is not jammed up against it
if ans==”Yes” or ans==”yes” # Accept uncapitalized or capitalized answers
# Note that a comment can go within a line of code
# You can also compare strings to each other, not just numbers
Ah – this code will not run; I left out one little but critical element of syntax. Can you fix it?
A “cheat sheet” for Python programming
Variables – types: string (‘gardenia’), integer (127), floating point (127.01)
Arrays – a set of variables or constants, such as myarray=[5,3,4,7]
Note that the entries count from 0, not 1, so, i=myarray returns the value 3 in the variable I
Inputs: all initials are strings unless we convert them:
i=input(“Enter a name”) stores any text we enter before hitting Enter into the string i
Note how the call to input can include a prompt, a text that gets printed; bare, it’s i=input()
i=int(input(“Enter a number”)) – on the fly changes out input to the integer value in variable I
Note that the number of parentheses must match
x=float(input(“Enter a floating-point number”))
Print – with or without prompt; always in parentheses
print(x) – will print the value of variable x
print(“The value of x is “,x,” in this section”) – obvious
print(6*x) – there can be math operations inside print
if x==’My name’ – note that double equal sign; we can compare strings
… and, to go further
print(“x is small”)
print(“x is medium-sized”)
print (“x is big”) – note that there can be a space between print and the content
Note that anything inside a control loop (an if statement, a for loop, etc.) has to be indented; Google Colab will do this automatically for you
Math – e..g, z=x+y, a=b/c
Built-in math –say we have array=[1,8,3]; then i=max(array) returns the value 8 in variable I
Fancier math – we can use import numpy to get things such as sines, exponentials, …
Concatenating strings: s=”My “+”name” creates in s the content My name
While condition; so, while True runs until we force a break; while x<10 goes until that condition becomes false
for i in range (0,nruns):
print(i) – This will print 0, then 1, 2, 3, 4; for´ always skips the last number!
Importing modules to add capabilities
import random as ran
x=ran.random() returns a random number between 0 and 1
print(t0) – this will give the UNIX timestamp, the number of seconds elapse since 1 January 1970!
We can use differences for timing, such as later calling t1=time.time() and computing dt=t1-t0
Drawing and plotting – lots of possibilities! Look at the codes you wrote
import matplotlib.pyplot as plot – this lets us use just plot when we want to use it
We were able to set how the figure axes appear, the limits in x and y of the plot area, how the markers for the points are colored and connection and sized
We used plot.plot(x,y…. ) (…. means other settings we choose) to set up the plot
We used plot.show() to make the plot appear
We also learned how to import IPython.display as ipd in order to play audio files
We learned to use this code to get access to text files we saved on our Google drives
from google.colab import files
uploaded = files.upload()
Reading an input data file
First, we have to give Colab access to our Google drive
from google.colab import drive
Then we have to read the data – an example:
from google.colab import files
filename=input(“Enter a filename “)
uploaded = files.upload()
with open(filename) as csvfile:
readCSV = csv.reader(csvfile, delimiter=’,’)
for row in readCSV:
Remember, when we create the data file using Google docs, we have to save it as a csv (comma-separated value) file- be sure to use download, the as txt and then change the extension in the filename to chop off the .txt that gets added
There’s always more to learn
Keep notes in class
Look up past programs that we wrote to see how we used things
You can always search for help, such as by typing “python 3 read csv file” in the browser address bar
Note that we’re programming in Python 3, such as Python 3.8; Python 2 is obsolete, so be sure you pick up hints for Python 3, not Python 2
You can always ask specifically for tutorials, such as “python 3 tutorial numpy”
You can always “hack,” meaning trying what you think will work. You may quickly find the right way to code something – e.g., you have to find out how a for loop should look; you write it but forget to have the colon at the end, or you forget that range skips the final value
There are very “elegant” ways to write code, with very compact specifications or with defining classes, etc.; we’ll stick to the basics
There are some cute things you might look up, such as dictionaries in Python or functions