OBJECTIVES

  • Learn how to use the Interpreter Prompt.
  • Introduce basic types like numbers, strings, booleans and lists.
  • Explain basic arithmetical operators, assignment and comparisons.
  • Show how to add comments to code.
  • Explain how Python uses indentation to denote structure.
  • Demonstrate what a function is, at a basic level.

INTRODUCING PYTHON

This section covers the basic Python knowledge required to understand the examples used throughout Part II of this book. If you are already familiar with Python, feel free to skip over to the next chapter.

We assume you are using Python 3 in this chapter.

images

In addition to this tutorial, you can find many good online tutorials here: https://wiki.python.org/moin/BeginnersGuide/
NonProgrammers

FIRST STEPS

You can run a Python program from the command prompt on your computer.

If you enter the python command, you should see something like this:

$ python
python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type ‘help’, ‘copyright’, ‘credits ’ or ‘license’ for more information.
>>>

This brings you into the Interpreter Prompt. Using this, you can enter Python instructions one line at a time and they will be executed immediately. This is useful for experimenting with small ideas. For example:

>>> x = 1 + 2
>>> print(x)
3

Alternatively, you can write your code into a text file and then have Python execute it all at once. If you were to write those same two instructions into a file called my_ code.py , you could run it like this:

C:\Users\Me > python my_ code.py
3

The code above uses the built-in print command, which causes the program to display the value which is contained in quotes. The traditional first step when learning a new programming language is to write a program that greets the world:

print(‘Hello, World!’)

Running the program from a source file 52 should look like this:

> python hello.py
Hello, World!

BASIC TYPES

Python allows you to process data of a variety of types. The most fundamental ones are already built into Python. These include:

  • Numbers like 7, 42 or 3.14
  • Strings, that is, an arbitrary sequence of characters. A string is denoted by being enclosed in quotes, either single ( ‘Hello, world’ ) or double ( “Hello, world” ). There’s no difference between choosing single or double quotes, it’s just a matter of choice. However, you must be consistent once you’ve made a choice.
  • Boolean values, that is, True and False .
  • Lists, that is, a sequence of items that are logically grouped together, like [1,2, 3] .

The examples used above are all literal values. A value can be assigned to a variable. The following code causes three different variables to be created:

the_number = 3
message = ‘Hello, World’
done = True

Variables allow you specify one set of steps that can be carried out on different values.

total_books = number_of_hardbacks + number_of_paperbacks

If you give the print command a variable, it will display the value of that variable.

>>> print(total_books)
41

Sometimes, you need to include the value of a variable inside a message. In Python you can simply do that by typing the variable name next to the string, separating them with a comma. For example:

>>> age = 35
>>> print(‘I am’, age, ‘years old.’)
I am 35 years old.

BASIC OPERATIONS

Manipulating data sits at the heart of computation. In a program, operations allow you to manipulate data. Python provides numerous such operations.

For example, you can manipulate numbers using arithmetic operators, like:

  • addition (for example, x = y + 2 );
  • subtraction (for example, x = y - 2 );
  • multiplication (for example, x = y * 2 );
  • division (for example, x = y / 2 );
  • exponentiation (for example, x = y**2 );
  • modulo, aka remainder division (for example, x = y % 2 ).

You can also use operations to interrogate values and establish facts about them. Such operations evaluate to True or False .

For example, the equality operator, \== , tests if two values are equal or not. This would display True :

x = 3 print(x == 3)

Whereas this would display False :

x = 3
print(x \== 4)

You can also compare two values to establish if one is larger or smaller, for example, this would display True :

print(3 < 4)

While this would display False :

print(9 < 4)

FUNCTIONS

A subroutine is a sequence of instructions within a program packaged up as a distinct block. They are the basic organisational blocks of a program.

The lines of code in a subroutine are not executed until the programmer explicitly requests them to be. When a subroutine is called on to execute its instructions, the flow of control jumps to that subroutine. When the subroutine has completed, the flow of control then returns to the point where the call took place.

Python supports a particular type of subroutine called a function. It behaves just like a subroutine except that it can also return values back to the calling line of code. In this code, two functions are defined (the keyword def is short for ‘define’):

images

The first one doesn’t return anything. The second returns the number 4.

You can call a function by typing its name followed by two parentheses:

images

Notice that the contents of each function are indented. This is how Python denotes that a line of code is part of a block. Any line that immediately follows a colon must be indented to show that it is contained in that block. All following lines that are similarly indented are considered part of the same block. The first line that’s not indented denotes that the block has ended. In the previous example, that means that the double_2 function contains the lines num = 2 * 2 and return num , but the three lines that follow are not part of the function.

When you call a function, you can pass an arbitrary number of pieces of data to that function which it can use. These are called parameters. For example:

images

COMMENTS

The previous example also featured comments (the lines that begin with a # symbol). When your program is being executed, any time the computer encounters a #, it ignores the rest of that line. This gives you the means to add comments that explain how your code works.

This is a comment. It will be ignored by Python, even if it# contains valid source code, like x = y + 1

SUMMARY

After reading the material in this chapter, you should be able to write short, basic programs using the Python programming language, either at the Interpreter Prompt or in a source file.

EXERCISES

For the following exercises, you need to write a program to answer the questions.

EXERCISE 1

Write a program that creates two variables, r and pi . Assign pi the value of the mathematical constant (or a suitable approximation of it) and give r any value you want.

EXERCISE 2

Use the variables from the previous question to create a third variable called area that holds the area of a circle with radius r .

EXERCISE 3

Write a program that creates two number variables, a and b . Give each variable a value and then use the print command to output True or False depending on whether or not a is greater than b .

EXERCISE 4

Take the code from the previous answer and write a function called bigger . This function should accept two parameters, x and y , and return a value denoting whether x is bigger than y . Add at least three calls to bigger with different values.