Programming Basics

Here are some basic programming examples to get you going.

Variables, equality, booleans

Assigning a variable. A single ‘=’ assigns a value to a variable.

 

Testing equality. A double ‘==’ tests equality.

 

Testing non-equality. A ‘<>’ tests non-equality.

 

You can also test inequalities: <, >, <=, >=.

 

Boolean functions. Some functions, like is_prime() and is_square() return True or False.

 

Defining a function

You can in fact make your own functions. Here’s one that squares whatever you give it. The command return tells it what to send back as its ‘answer’. When you evaluate this it won’t print anything since it is just defining the function (creating it in memory).

 

Here’s how you can use the function you made.

 

Conditionals and cases

Booleans (thing returning True/False) can be used in if/else statements. You should indent the portion of code that depends on the Boolean.

 

Loops

A for loop will loop through a prescribed range. (It creates the range first, which takes computer memory.) Indentation matters. Notice how `range(1,n)’ doesn’t include the endpoint ($n$).

 

A while loop will keep repeating until you tell it to stop. It’s a bit more work to set up than a for loop, but it doesn’t create the whole range beforehand. To control the loop, you use any Boolean, i.e. anything which returns True or False.

 

Here's a while loop that will find the first integer >= 2 which is composite:

 

Here's an example of a while loop which looks for an integer with exactly 3 factors.

 

Here's an example of a while loop which looks for an element of a specified multiplicative order modulo $n$.

 

Random numbers

Here's a standard way to get a random integer in a given range:

 

Lists

Lists (which are ordered) are often very useful. Here's how to initialize a list with a sequence in it, in this case the first 10 squares. It's similar to set builder notation.

 

Here's a way to do the same thing with a loop. It demonstrates how to add elements to a list.

 

You can make a list of primes:

 

You can call elements of a list by their positions:

 

A little exercise, and advice

A general hint to avoid confusing bugs: Build your code in testable steps. For example, if you want to run a loop which does thing A repeatedly, program thing A without the loop first, and make sure it is all working, then build the loop you are interested in with nothing inside, and test that, before combining them. You may also wish to use print statements so you can watch what your code is doing step-by-step.

To test your skills, create a while loop which finds the first integer greater than 101 which is square. You can use the function is_square() to check if something is a square. It returns True or False.