In order to test pieces of code we can run Python from the command line. In this Jupyter Notebook we are going to simulate this. You can type the commands in the fields and execute them.
In the field type:
<shift> + <return> to execute the command.
You just created a program, that prints the words 'Hello, World'. The Python environment that you are in immediately compiles whatever you have typed in. This is useful for testing things, e.g. define a few variables, and then test to see if a certain line will work. That will come in a later lesson, though.
20 + 80
and execute the code.
These are additions. We can of course use other mathematical operators.
Try this subtraction:
6 - 5
and this multiplication:
2 * 5
5 ** 2
** is the exponential operator, so we executed 5 squared.
print('1 + 2 is an addition')
You see that the
print('one kilobyte is 2^10 bytes, or', 2 ** 10, 'bytes')
This demonstrates that you can print text and calculations in a sentence. The commas separating each section are a way of separating strings (text) from calculations or variable.
Now try this:
23 / 3
23 % 3
% returns the remainder of the division.
Remember that thing called order of operation that they taught in maths? Well, it applies in Python, too. Here it is, if you need reminding:
Here are some examples that you might want to try, if you're rusty on this:
1 + 2 * 3 (1 + 2) * 3
The final thing you'll need to know to move on to multi-line programs is the comment. Type the following (and yes, the output is shown):
# I am a comment. Fear my wrath!
A comment is a piece of code that is not run. In Python, you make something a comment by putting a hash in front of it. A hash comments everything after it in the line, and nothing before it. So you could type this:
print("food is very nice") #eat me
This results in a normal output, without the smutty comment, thank you very much.
Now try this:
# print("food is very nice")
Nothing happens, because the code was after a comment.
Comments are important for adding necessary information for another programmer to read, but not the computer. For example, an explanation of a section of code, saying what it does, or what is wrong with it. You can also comment bits of code by putting a
# in front of it - if you don't want it to compile, but can't delete it because you might need it later.