Advertisement

Thursday, 20 April 2017

Just Enough Python 3


If you have gone through the first two tutorials, you will now have Geany setup and will have written and run a simple program.

In this lesson we are going to see how to make decisions, and along the way we'll get to grips with Python libraries.


Making decisions is a fundamental operation in programming. If a button has been pressed in a game, some sort of action needs to be taken and we need to decide what action is taken.

We are going to illustrate this idea by changing the output of our simple greeting program depending on the time of day.




Python libraries

So, a Python library must be where a snake goes to borrow books, right? 

In reality, a programming library is a repository of software, rather than books. A library contains a set of functions and these functions have been written to make our programming life a bit easier. In Python, these libraries are called packages. 

Remember, the input and print functions from last time? These are  built-in functions. But not all functions can be built in, it would make Python too large. So functions that are useful but that won't be used in all programs need to be included specifically. We are going to use a package called datetime. You can probably guess what it is for!

So packages contain functions,  and we can just import the package that we need from the library. Something like this:

import packagename

Packages can also contain sub-packages which, in turn, contain functions. We would import a sub-package like this

import subpackage from package

So, back to getting the time. Confusingly we want to use a sub-package is also called datetime, so we use this to import the datetime sub-package:

from datetime import datetime

This means that we want to import the sub-package datetime from the package that is also called datetime.

So far, so confusing (well I hope not!).


And how do we use this new sub-package? It contains functions that are useful for messing around with time. The function that we are interested in is called now(), which gives us the current time.

Time for a program!

Create a new program called 'example3.py' (or whatever you want to call it) and type in the following:

from datetime import datetime 

currentTime = datetime.now()

print(currentTime)

Run it and you see the time displayed, something like this:


As you can see it prints the current date and time in a standard format.

The first line imports the datetime sub-package from the datetime package. The next one introduces a variable called currentTime and gives it the value of the now() function in datetime. Notice how we do this. We use the name of the sub-package, datetime, follow it with a dot, and then the function name. Also note that a function is always followed by a pair of braces, even if we are not passing any data to that function. 

So now the variable currentTime contains the value of the current time (and date). And the we print it.

But it can do more!

What you see when you print the result is the 'string representation' of currentTime, in other words, it's printed the way that we would want to see it. But the variable actually contains separate values for each part of the date. It contains the year, the day, the month, the hour, etc. all as separate values.

And the good thing is that we can get at them easily. Try this:

from datetime import datetime

currentTime = datetime.now()

print(currentTime.year)

You we put a .year at the end of currentTime. This means give me the part, or attribute, of currentTime that contains the value of the year. So that is what is printed.

Decisions, decisions!

Now, write a new program. (The layout of the program is important. Geany will automatically indent text for you when necessary, so that means when you hit return after response = "Good morning "+name, you will need to do a backspace to get the cursor back to where you want it).

from datetime import datetime

name = input("What's your name: ")
currentTime = datetime.now()

if currentTime.hour < 12:
 response = "Good morning "+name
else:
 response = "Good afternoon "+name
 
print(response)


You know what most of this does and you can probably work out those bits that you don't know. However, we need to explain what is happening and (this is very important) exactly what the form of the program is - what the correct syntax is.

Let's begin with the line starting with if. You know what currentTime.hour is, it gives us the value of the hour part of currentTime - an integer value between 0 and 24.

You will not be surprised that the < means less than and so the expression currentTime.hour < 12 means is the the value of currentTime.hour less than 12. The answer is either true or false.

The if looks to see if the next part is true or false and, if it is true, it will move on the the statement(s) that follow. If it is false, it will skip to the lie beginning with else. Note that the if line ends in a colon, the program won't work if it is not there.

The statement that follow the if (in this case only one) must be indented. This is unique (I think) to Python. Most languages don't care about layout but Python is very strict about it.

The next line is else: and, again the colon is essential. The lines that are indented after else: are executed only if the if test result was false.

Now you can see how decisions are made in Python but there is rather more to the if statement which I shall now explain a little more formally.

if: else: more formally


What we are talking about here is the if statement. It consists of the word if followed by a test that results in a true or false answer followed by a colon.

If the result is true then the statements following the if statement are executed. These statements must be indented.

If the the result of the test is false, the indented statements following the if statement are ignored and the indented statements following the else: are executed.

The else: line is optional. If it is not included there are no more indented statements and the program carries on as normal. So we could have written:

from datetime import datetime

name = input("What's your name: ")
currentTime = datetime.now()
response = "Good afternoon "+name
if currentTime.hour < 12:
 response = "Good morning "+name
 
print(response)

This would have the same result as the original program.

The test can use a number of operators:

==
   e.g. if a == b (if a is the same value as b then the answer is true, otherwise false)

!=
    e.g. if a != b (if a is NOT the same value as b then the answer is true, otherwise false)

<
    e.g. if a < b (if a is less than the value of b then the answer is true, otherwise false)

>
    e.g. if a > b (if a is greater than the value of b then the answer is true, otherwise false)

<=
    e.g. if a <= b (if a is the same value as b or less than the value of b then the answer is true, otherwise false)

>=
    e.g. if a >= b (if a is the same value as b or greater than the value of b then the answer is true, otherwise false)

The next tutorial is here.

6 comments:

  1. Sorry for being so disturbing, I am really trying your tutorials. But the last 3 white boards that had to have the example codes are empty in my browser(firefox)...

    ReplyDelete
  2. In fact they aren't empty, when I've selected the (empty) text, it magically appeared. Background is the same colour as the text.

    ReplyDelete
    Replies
    1. I just wanted to let you know that I really appreciate your comments :)

      Delete
  3. Fábio, thanks very much for pointing this out. I'll look at it now and get back to you asap.

    ReplyDelete
  4. I've repeated the code outside of the boxes as a temporary measure until I work out what's wrong with my template. Apologies.

    ReplyDelete
  5. For clarity, the code is no longer in the boxes.

    ReplyDelete