Basics#
Calculations#
Below is a list of some typical operations. What might stand out is that exponentiation is done with **
and not ^
. Write 2**4
for \(2^4\). It happens that ^
still runs, but it does something else.
Operator |
Description |
---|---|
|
Addition |
|
Subtraction |
|
Multiplication |
|
Floating point (normal) division |
|
Exponentiation |
We can use parenthesis for readability and to order operations in the usual way.
1 - 1 * 0
1
(1 - 1) * 0
0
Variables#
A Python variable holds a value. It can be text, a number, or perhaps a more complicated data type. Variable assignment is done with the equals sign, =
. Below we, we create a string variable called greeting
and a integer variable called my_favorite_number
.
greeting = "Hello, World!"
my_favorite_number = 91
The print
function will display the value in the output. Compare the output you get from the following. We reference the actual variable with greeting
, not when using quotes for "greeting"
.
print(greeting)
print("greeting")
print("Hello, World!")
print(91)
print(my_favorite_number)
print("my_favorite_number")
Hello, World!
greeting
Hello, World!
91
91
my_favorite_number
Note that while \(x = x+1\) is nonsense as a mathematical equation, in Pythonx = x + 1
simply adds one to the value of x
.
x = 0
x = x + 1
x = x + 1
print(x)
2
Aside: There happens to be a shorter syntax for the above. x = x + 1
can be replaced by x += 1
. This is more Pythonic, but not a big deal.
x = 0
x += 1
x += 1
print(x)
2
Comments#
Commenting your code is helpful if you care about your colleagues or your future self. Comments should add clarity to the intention and workings of code. A comment is a piece of code that isn’t actually executed-it’s a comment left for the reader or the person who inherits and modifies your code. Everything after a
#
will be ignored by Python.You might also use end-line comments like the following.
Perfect comment technique does not correct for bad code though. Compare the following blocks of code.
The first block is commented and the second is not. Still, the second code block is better because the variable names are chosen so you don’t need comments. Good naming becomes even more important as the program becomes longer, variables are used over and over, and you start working with collaborators.
In this case, longer and more descriptive variable names are preferable to shorter variable names. If one program can do the same thing as another with fewer characters, that doesn’t make it better. Code golf is a kind of recreational coding where one tries to get from point A to point B in as few characters as possible. Being a good code golfer is not the same as being a good coder.