Youssef Boubli

Personel blog

Very simple programs

Introduction OK! We have python installed, now what? Well, we program! And it is that simple (at least for now). Python makes it easy to run single lines of code - one-liner programs. Lets give it a go.

Opening IDLE Go to the start menu, find Python, and run the program labelled ‘IDLE’ (Stands for Integrated Development Environment.

Now you are in the IDLE environment. This is the place you will be spending most time in. Here you can open a new window to write a program, or you can simply mess around with single lines of code, which is what we are going to do. Type the following and press enter: (don’t type »> as it should already be there)

	>>> print "Hello, World!"

What happened? You just created a program, that prints the words ‘Hello, World’. The IDLE 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.

Math in Python

Now try typing the stuff in bold. You should get the output shown in blue. I’ve given explainations in brackets.

	>>> 1 + 1
	2

	>>> 20+80
	100
	>>> 18294+449566
	467860
	(These are additions)
	>>> 6-5
	1
	(Subtraction)
	>>> 2*5
	10
	(Multiply, rabbits!)
	>>> 5**2
	25
	(Exponentials e.g. this one is 5 squared)

	>>> print "1 + 2 is an addition"
	1 + 2 is an addition
	(the print statement, which writes something onscreen)
	>>> print "one kilobyte is 2^10 bytes, or", 2**10, "bytes"
	one kilobyte is 2^10 bytes, or 1024 bytes
	(you can print sums and variables in a sentence.
		The commas seperating each section are a way of
		seperating clearly different things that you are printing)

	>>> 21/3
	7
	>>> 23/3
	7
	>>> 23.0/3.0
	7.6666...
	(division, 2nd time ignoring remainder/decimals,
		3rd time including decimals)
	>>> 23%3
	2
	>>> 49%10
	9
	(the remainder from a 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:

  • 1- parentheses ()
  • 2- exponents **
  • 3- multiplication , division \, and remainder %
  • 4- addition + and subtraction -

Order of Operations

Here are some examples that you might want to try, if you’re rusty on this:

```python »> 1 + 2 * 3 7 »> (1 + 2) * 3 9 ``