Coding Basics - in Python

Acknowledgements

This code was developed and written for the benefit of the SMU Honors Physics Course (PHYS 1010) by these authors:

And is freely available for download at https://github.com/stephensekula/smu-honors-physics/

Table of Contents

Basic Python

Here we will demonstrate how to do simple coding in python. The most basic program you can write will begin with a "data member" (e.g. a number, such as "1") and execute its arithmetic "operators" (e.g. addition, subtraction, multiplication, and division) on another data member in order to combine them under that operation. See below for examples. Feel free to change examples! Play around. To learn, we must play!

Simple Arithmetic

Simple Math Commands available for number data type are: "$+$" (addition), "$-$" (subtraction), "$*$" (multiplication), "$/$" (division), and "$**$" (exponential)


In [1]:
1+1


Out[1]:
2

In [2]:
2*3


Out[2]:
6

In [3]:
2**4


Out[3]:
16

Be Careful

Python cares about decimal points. If the first number in an operation is without a decimal place, Python treats it as a pure integer and all subsequent operations are done using integer arithmetic (no decimal places, and rounding is applied!). If the first number contains a decimal place, the operations are treated as "floating point operations" - decimal number arithmetic, with remainders represented as decimal fractions. See examples below.


In [4]:
2/3


Out[4]:
0.6666666666666666

In [5]:
2.0/3


Out[5]:
0.6666666666666666

In [6]:
2/3.0


Out[6]:
0.6666666666666666

In [7]:
2.0/3.0


Out[7]:
0.6666666666666666

Variables

A "variable" is a placeholder for some data, known or unknown in advance. This is just like variables in algebra, e.g. "x". You can define arbitrarily named variables and store numbers in them, then act on them symbolically without knowing their actual values, like so:


In [8]:
a = 9.8
m = 70
F = m * a

In [9]:
F


Out[9]:
686.0

Nota Bene!

There are limits to how arbitrary you can name variables. You CANNOT name a variable:

  • after an existing function in Python, e.g. print = 1 will fail, since print() is a function in Python that prints its contents to the screen.
  • with spaces or many other special characters in its name. my_cool_variable = 5 is okay (underscores are allowed), but NOT things like my cool variable = 5 or my-cool-variable = 5. Spaces separate data types and/or operations in a command, and dashes mean "subtraction" in Python.

Complex Numbers

You are not limited to real integers and decimal numbers! You can represent complex numbers with both a real and an imaginary part, e.g.

$$ z = x + i y $$

where

$$ i = \sqrt{-1}$$

One concrete example complete number is:

$$ z_1 = 5 + 6i $$

where the real part is 5 and the imaginary part is 6. To add two complex numbers, add the real parts and imaginary parts separately (in other words, treat $i$ as a common factor that can be pulled out in front of the imaginary part!)

(by the way, notice above that we rendered nice-looking math equations in this Python notebook. How did we do this? An AWESOME mathematical and text typesetting language called LaTeX that can be embedded right into these notebooks. Double-click on this cell to see the raw LaTeX code. LaTeX is a programming language, just like Python, except instead of telling a computer how to execute instructions it tells a computer how to format text in a beautiful way, far better than any word processor is able to do).


In [10]:
z1 = complex(5,6)
z1


Out[10]:
(5+6j)

In [11]:
z2 = complex(1,2)
z2


Out[11]:
(1+2j)

In [12]:
z1 + z2


Out[12]:
(6+8j)

Loops

This is all fun, but what if we have to do a repetative task? Do we code up each step in the task? No! We use "loops" to automate the task. For instance, if we wanted to print the first 10 numbers from 0-9, we could write this code:

print(0)
print(1)
print(2)
print(3)
print(4)
print(5)
print(6)
print(7)
print(8)
print(9)

But this is tedious! Programming was supposed to make our life easy! If only there was a way to instruct the computer to step forward, one-at-a-time, through the numbers from 0-9 and print each one. There is: it's called a "for loop". The for command instructs the computer to set a variable to values in a range, step through each value, and execute code each time on the variable.

Letting the computer do your work for you:


In [13]:
for x in range(0,10):
    print(x)


0
1
2
3
4
5
6
7
8
9

Functions

The for loop and the print call are examples of using built-in functions to execute a task. What if you want to define your own?

We can! There is a syntax for defining any kind of function we like. It takes in data and spits out new data, according to the recipe inside the function. This lets us store commands in a certain order and use them over and over again, without having to write the code EACH TIME to do so.

This is part of a common philosophy in code: reuse and recycle. Write once... execute many times!

For instance, here is a custom function for squaring the value of a variable x and returning the value of that operation:


In [14]:
def square_me(x):
    y = x**2
    return y

In [15]:
square_me(2)


Out[15]:
4

In [16]:
square_me(16)


Out[16]:
256

In [17]:
square_me(101)


Out[17]:
10201

Lists

What if we have special sequences of data that we want to store and then process? Storing a lot of things in one place is what "lists" allow us to do! We can even combine lists with for loops and functions to do cool things to each data member in the list. For instance:


In [18]:
my_list = [1,2,3,4]

In [19]:
len(my_list)


Out[19]:
4

In [20]:
my_list[0]


Out[20]:
1

In [21]:
my_list[2]


Out[21]:
3

This one will send an error back because in PYTHON, lists start numbering at 0 and go to the length-1


In [22]:
my_list[4]


---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-22-d8d3b5435ffd> in <module>
----> 1 my_list[4]

IndexError: list index out of range

Putting it all together

Let's combine our skills! Let's use the list (my_list), for-loop over its contents, and square each one, printing the result!


In [ ]:
for x in my_list:
    print( square_me(x) )