Introduction to Python

In this section, we're simply going to be introducing Python and making our very first app. In this introduction to Python, we're going to be going over installing Python, and using IDLE, which is a development environment that comes with Python.

We will also look at what variables, strings, and integers are- (just types of data the computer can hold)

Then we're going to be looking at methods and parameters, and then we're going to be going into creating our first app. The app is going to be called "Our Age in Seconds", and this is going to be a simple program that takes our age in years and then gives it back to us in seconds.

As you can imagine, this will be a very simple program, as calculating our age in seconds is just a matter of multiplying our years by a few numbers. There's 365 days in a year (without counting gap years), 24 hours per day, 60 minutes per hour, and 60 seconds per minute.

So our age in seconds would be our age in years multiplied by 365 * 24 * 60 * 60.

Installing Python

To install Python, all you have to do is go to http://python.org and download Python 3.5. This is the version used in this book and throughout the course, but Python 2.7 will also work just as well, and later versions should also work.

If when you are taking the course, a Python version like Python 4 has come out, it is not clear whether it will work or not, and so it is advisable to use Python 2.7 or Python 3.5.

Installing Python should just be a matter of double-clicking the downloaded package and installing as normal.

Once that is installed, you will have Python in your computer, which lets you create and execute Python programs! You will also have access to IDLE, the Python Shell, which lets you create Python programs interactively, and is a great tool to get started with Python.

Open up the program IDLE, and let's get started with Python!

Python 101

IDLE is an interactive Python shell, which means that whenever you write a Python line of code, it will instantly get evaluated and the result given back to you, if there is a result to give back.

In some instances, a line of code may not give back a result, it may just perform a calculation or assign a value.

Try typing 5+5 into the IDLE program.

You'll see that 10 is shown instantly, as that is what Python would evaluate the expression 5+5 to be.

Now try typing the following code into IDLE:

>>> "5" + "5"

And you'll see that what comes back is '55'. This is because what we added there are not two numbers, but rather two strings. Strings--also sometimes known as literals--are just sequences of characters. When we tell Python to add two sequences, the only thing it knows to do is concatenate them; i.e. join them together.

Going one step forward and typing the following:

>>> "5" + 5

You'll see an ugly error. Python does not know how to add a string and a number together, because they are intrinsically different types.

Remember, computers are not intelligent. Computers know how to do things because we, the programmers, told them how to. Python can only do what the creators of Python can do, no more.

Variables in Python

Working with numbers and strings is all good and dandy, but it does not have much use if we can't persist the values we are calculating for them to be used later on.

Thus we can save our calculations into boxes. Each box can hold one value, and each box has a name. We can give a box whatever name we want, as long as it doesn't start with a number and doesn't have any special characters except the underscore (_).

In IDLE, we may create some variables like so:

>>> x = 5 + 5
>>> z = "123"
>>> my_variable = 15465788
>>> user_name = "Jose"

Notice that the following variable names are invalid, and Python will complain if you attempt to name your variables like any of the following:

>>> 1var = "A string"
>>> currency$ = "Dollar currency"
>>> email@server.com = "jose@schoolofcode.me"

Interacting with Users

Although in IDLE we can just type our expression and it gets evaluated (e.g. typing 5+5 prints out 10), normally Python would not print anything out for the user to see unless we explicitly tell it to.

We can tell Python to print something by using the print() command, like so:

>>> print("Hello, world!")
Hello, world!

When we tell Python to print something--it can be strings, or numbers, or anything else--it will appear in the text-based output for the user to see.

For example, if the user's age was 30 years old, we could print out the user's age in seconds using a simple program:

>>> user_age = 30
>>> user_age_in_seconds = user_age * 365 * 24 * 60 * 60
>>> print("Your age in seconds is " + str(user_age_in_seconds))

Easy, isn't it!

In the last line, we need to use the str() method to temporarily treat the number that is user_age_in_seconds as a string, so it can be concatenated with the literal string. Remember that if we try to add a string and a number, we will get an error!

However, in order to do that we have to initialise our program with the user's age. That makes it difficult for the user to get their age in seconds, as they can't tell the program how old they are!

Lets change the program so it asks the user for their age first, and then we'll explain how the program does it:

>>> user_age_string = input("Enter your age: ")
>>> user_age_int = int(user_age_string)
>>> user_age_in_seconds = user_age_int * 365 * 24 * 60 * 60
>>> print("Your age in seconds is " + str(user_age_in_seconds))

There are a couple changes with respect to the previous version:

  • user_age_string is no longer the static value 30, but rather it is whatever the input() function returns. This function will print out Enter your age: to the user, and then the user can input the number, which the program will save as a string into user_age_string.
  • user_age_int is the converted user_age_string into an integer. Integers are just whole numbers, and Python treats them slightly differently to floating-point numbers (numbers with a decimal place).

Then we use user_age_int as the user age, and we calculate the age in seconds and print it out to the user.

The input() and the print() methods both print something to the user, but with the difference that the input() method allows the user to type something back, and that can get saved into a variable.

The format() method

There is an extremely useful method that we can use instead of having to add strings together:

...
>>> print("Your age in seconds is " + str(user_age_in_seconds))

That is ugly code, and you need to remember the space at the end of the literal string, so that the literal and the variable don't appear together. You also need to remember the str() function, or else you'll get an error.

Instead, we can do this, which is simpler and will allow much greater flexibility later on:

...
>>> print("Your age in seconds is {}.".format(user_age_in_seconds))

What that tells Python is to swap the set of curly braces ({}) by the element that is between the brackets of the format() method.

We can do that with more than one element:

>>> print("My name is {}, I am {} years old.".format("Jose", -1))
'My name is Jose, I am -1 years old.'

Remember that Python is not smart, so me being -1 year old is absolutely fine!

Advanced usage

We can do more advanced things with the format() method, but these are not essential. Feel free to skip them if you want to proceed quickly into the next part of the course.

We can name parameters to make the whole string more readable:

>>> print("My name is {name}, I am {age} years old.".format(name="Jose", age=30))
'My name is Jose, I am 30 years old.'

Here the value inside the curly braces (e.g. {name}) is what Python looks at when swapping, and so it knows to swap "Jose" for the {name} token.

This means that the parameters to the format() method need not be in order:

>>> print("My name is {name}, I am {age} years old.".format(age=30, name="Jose"))
'My name is Jose, I am 30 years old.'

It also means we can re-use a parameter:

>>> print("My name is {name}, is your name {name} too?".format(name="Jose"))
'My name is Jose, is your name Jose too?'

These things are a lot more is what you can do with the format method. The course contains a cheatsheet which you can download and optionally print out, and contains a reminder of what was covered here for your convenience.

Methods in Python

Normally when we are working on developing a program, we want it to be readable. This is so that when we go back after weeks or months, we can easily dive in and change things that need to be changed (for example, if we realize that something isn't working quite as we intended).

It is extremely difficult to do this if our program is just one bit set of single-line expressions, so it is better to give names to groups of expressions, so that we can more easily and quickly understand what the groups do. For example, we could give a name to the group of expressions that asks the user for their age and converts it to a number:

>>> def get_user_age():
        user_age_string = input("Enter your age: ")
        user_age_int = int(user_age_string)
        return user_age_int

What this accomplishes is that now we can just execute get_user_age(), and that will ask the user to input something, wait for the user to write it, then convert that to a number, and give us back the value.

Try it yourself!

What we have done is created a method called get_user_age that will execute all expressions it is associated with. Python knows which expressions it is associated with because those expressions are directly below the method and indented consistently.

For example, the following code would be valid:

def get_user_age():
  user_age_string = input("Enter your age: ")
  user_age_int = int(user_age_string)
  return user_age_int

But the following code would not be valid, because the indentation is not consistent:

def get_user_age():
  user_age_string = input("Enter your age: ")
user_age_int = int(user_age_string)
  return user_age_int

Indeed, Python would assume the expressions associated with the method get_user_age finish after the first line below it, where the indentation ends. The line that says return user_age_int would then be marked as an error because Python does not understand why it is indented. After all, it does not belong inside a method because the line above it breaks the association with the method.

Methods can also use values that are given to them, like so:

>>> def calculate_age_in_seconds(age_years):
        return age_years * 365 * 24 * 60 * 60

Here, we are telling Python that this method will accept a value, and that that value will be stored in a variable called age_years. We can then use this variable inside the method, but only inside the method. The variable age_years will not exist outside this method.

We can use more methods, and call a method from within another method, and thus we could end up writing our age program with the following methods:

>>> def get_user_age():
        user_age_string = input("Enter your age: ")
        user_age_int = int(user_age_string)
        return user_age_int
>>> def calculate_age_in_seconds(age_years):
        return age_years * 365 * 24 * 60 * 60
>>> def run():
        print("Your age in seconds is {}.".format(calculate_age_in_seconds(get_user_age())))
>>> run()

Take a few minutes to analyze the code and understand what is happening in it, and what each method does.

Inside the run() method, we are calling format() using whatever comes out of calculate_age_in_seconds(). To that method we are passing the output of get_user_age, which as we know returns the user's age as a number.

Simplifying get_user_age()

We could simplify get_user_age() and make it shorter, if we wanted.

Some might see the simplifications as making it more complex and difficult to read; others may not. Remember in most cases in programming, how you do something doesn't matter much, as long as the outcome is correct and the code is readable.

We could simplify to this:

def get_user_age():
  user_age = input("Enter your age: ")
  return int(user_age)

Or we could simplify further, to this:

def get_user_age():
  return int(input("Enter your age: "))

It is completely up to you how you want to do this.

When you are working with a team, you should all come up with common coding style that you all agree with, to simplify working with each other's code.

results matching ""

    No results matching ""