ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Programming Languages

How to Program using the Python Programming Language for Beginners

Updated on August 19, 2016

Introduction

This is a tutorial on learning how to program using the Python programming language for beginners. It’s a popular language and it is the official language for programming the Rasperry Pi computer. There is now a version 3 of Python with a number of changes from Python 2. We will use Python 2 because it is still in common use.

This tutorial will get you started very quickly by teaching you programming structure using the Python Language. In any programming language, you need to learn how to program inputs, decisions, iterations, and output. These are the building blocks of a programming language. Once you have understood these concepts, you can begin to solve many programming tasks. Most newer programming languages nowadays are object-oriented as well, and while it is possible to solve a lot of problems without it, it is best to learn object-oriented programming if your language supports it. Python is object-oriented but this will be covered in later tutorials.

Learning Python on a modern PC

The very early computers didn't have much in the way of interacting with users.

It had inputs, processing and outputs, but you programmed the inputs as part of the program. The inputs are "hard coded" into the program and some programs were done on "punched" cards and fed into the computer using machine language instructions.

Computers have evolved a lot since then and now offer things such as the keyboard, mouse, and touch screen as inputs. They can use colour displays, sounds and printers as outputs. Programming languages have evolved to make it more easier to learn and become more "English" like. Some programming languages were created to take make writing certain types of applications easier. Python itself was created with a philosophy of code readability and allowing programmers to express concepts in few lines of codes than other languages such as C++ or Java.

Why did I touch on the above before giving a tutorial on Python ? I want to de-mystify programming.

Try to understand that programming is giving a set of instructions to a computer. A programming language is just a tool to make a computer do what you want.

Learning to program is learning how to use the tool.

I chose Python because Python's syntax is quite easy to read and follow. It is quite a popular language and in some cases it is the chosen language for that computer system. The Raspberry PI computer uses Python as it's de-facto language and the PI was invented to try to get more children into computing and programming.

Python can also be used to write apps for mobile platforms such as Android and Apple iOS with some workarounds. These workarounds (such as Kivy) will in time become mature and accepted as the norm.

So let's get Started!


Downloading Python 2

Launch your favourite browser, and go to the following link:

http://www.python.org/

Find the Python 2 release and follow the link to download the appropriate version for your operating system.

Once you have downloaded the installer, you can install it using the default settings.

In this tutorial, we will be looking at the Windows version.


Hello World

It is now customary at the beginning of learning a programming language to write a small program to print “Hello World”.

So let’s begin:

Open up IDLE (Python GUI) :

Type in the following and press Enter:

print (“Hello World”)

Now type in:

print “Hello World” ( See screen shot below).

NOTE: Python 2 allows us to not use parenthesis if we don't want to, but Python 3 requires that a parenthesis is used because "PRINT" is a function. We will try to wherever we can use the Python 3 convention.

Print command

Some of the most useful commands in any programming language are the commands to display messages to the user.

In Python, one of the commands is the print command.

The print command allows you to print words and sentences that are enclosed in double quotes.

For example:

print ("My name is John Smith")

It also allows you to print numbers and do calculation on the numbers.

For example:

print 5
print 5 + 6


The numbers MUST NOT be included in double quotes. If it is included in double quotes, it will be treated as text and mathematical calculations cannot be performed on it.

For example:

print ("5 + 6")


Exercise

Try printing your own name.

Numbers and Mathematical Operations

The following are the mathematical operators that can be used with numbers. Numbers can be integers (whole numbers) or fractions. Fractions are called floats in Python (and in most other programming languages). With Python, you can simply use Python as a calculator by typing the mathematical operations at the Python command prompt. e.g.

>>> 5 * 3  (press Enter)
15
>>>


In Python, if you enter the operands (numbers) as whole numbers i.e. without a decimal point, the result is also an integer.

The symbol * is a multiplication operator.

     Example : 
               >>> 5 * 2
               10
               >>>


The symbol / is a division operator.

Note: The resultant answer will depend if it is an integer division or float division.

To make an expression an integer division, only use whole numbers. 
Even if the result is a float, only the whole number part is returned 
as the answer. The remainder is discarded.

     Example of an Integer division :
               >>> 10 / 3
               3
               >>>

To make an expression a float division, you must include a decimal 
point for one of the numbers in the expression. The result will then
include the remainder.

     Example of a Float Division :
               >>> 10 / 3.0
               3.3333333333333335
               >>>



The symbol // performs division but returns only the non-fractional part.

     Example : >>> 10 // 3.0 
               3.0 
               >>>


The symbol % is the mod operator. It performs a division but returns the remainder as a whole number for float division.

Example :

               >>> 20 % 3.0
               2.0
               >>>



The symbol + is the addition operator.

      Example : 
               >>> 10 + 20.0
               30.0
               >>>



The symbol - is the subtraction operator.

      Example: 
              >>> 20.0 -11.0
              9.0
              >>>

The symbol ** is the power of symbol.

      Example (5 to the power of 2): 
               >>> 5 ** 2
               25
             >>>


Exercise
Perform any calculations you like so you can understand how the above operators work.

A Simple Python Program

Let’s get started now writing a simple program using Python.
Before writing a program, you need to know what it is that you want the program to do.

I’ve learnt many years ago that most programs consists of Input, Processing, and Output (IPO for short).
If you have an idea of what the program is going to do, you should sit down and work out what are your Inputs, what are your Outputs, and what is required to be done to the Inputs, which is the Processsing. You can divide a simple white piece of paper into three columns. The first column is Input, the second column is Processing, and the third column is Output. Even though the column is ordered this way, you will usually start filling out either the Output or the Input columns first. But it really doesn’t matter as now you are brainstorming what information your program will need and what functions are needed to achieve the desired outputs.

For example:

I want the computer to ask me my name and then say hello to me.

For my Input, I will need the following:

my name

For my Output, I will need the following:

Say hello to my name

Therefore, for Processing, I will need to do :

Get my name and print hello to my name

We can see that in processing we need at least two commands (or functions) to do what we want i.e. get my name, print my name.

Let’s convert those statements to Python statements.

myname= raw_input()
print “Hello ” + myname


Open up IDLE (Python GUI) :

1. Select File, New File

2. Type the following:

myname= raw_input()
print “Hello ” + myname

3. Select Run, Run Module

It will prompt you to save the file.

The IDLE window (Python Shell) is running the program. You can see the “RESTART” message.
Our program now is running and there is a blinking cursor. We know from writing the program that it is waiting for an input from the user. Now type in your name, and press Enter.

Adding Bell and Whistles

While we know what the program is doing and can deduce that the blinking cursor is waiting for you to type something, nobody else is likely to know that. This is the time to start adding “bells and whistles” to our program and make it more intuitive and nice to use.

The raw_input() function takes a string parameter and displays this on the screen before the blinking cursor.

Let’s modify our program to add a message “What is your name ?”

1. Go to the IDLE (Python GUI) editor.
2. Modify the source code to the following :

myname= raw_input(“What is your name??)
print “Hello ” + myname

Now run it.

Python Statements

Statements are what you write to tell Python what your program should do. Essentially they are instructions that you write in the Python language, and the Python interpreter
will interpret and execute your commands.

An example of Python Statements

- "print" is an example of a statement (it is a function also)

- if/elif/else are statements that are used to determine program flow and actions/statements

- for/else are statements that can be used to conditionally repeat certain actions/statements

- while/else are statements that can be used to create a loop or repition of sections of statements until a particular condition is met before the program continues to the
the next section

Statements can contain the following :

- Assignment operations e.g. a=b, where '=' is the assignment operator

- function calls

Program Flow and Control Structure

Programs contains statements or instructions that gets executed one after another. Sometimes depending on particular "events" or "conditions", a certain statement is executed instead of another. In some situations, we want to repeat particular statements until a certain condition is met. This is known as the program flow, and we use control structures to control the flow of our program.

Of very important note is that in Python, we MUST indent statements to make sure it gets interpreted properly in the program control structure that it belongs to. It's not just indented for the sake of clarity. The program will actually either error out (which is relatively good) or produce incorrect results (which is relatively bad) .

The "if" Statement

The if statement allows a particular sequence of statements to be executed if a condition is true, or allows a particular sequence of statements to be executed if that condition is false. It allows the testing of alternative conditions by using the elif statement to check for another condition.The if/elif/else control structure is single pass meaning that there is no re-iteration (or repeating of the statements) by default. If the condition or conditions needs to be re-tested so that appropriate actions via the program statements are executed depending on the condition, the if/elif/else structure needs to be combined with other control structures which supports re-iteration to be able to achieve this..

The syntax of the if statement is below. Note: The square brackets [ ] means optional :

if condition : [ statement... ]
  [ statement....
    statement.... ]
[elif condition : [ statement... ]
    statement....
    statement.... ]]
[else : [ statement... ]
  [ statement....
    statement.... ]]


Type the following as a program in IDLE and run it. (NOTE: You have to select Run again if you want the program to ask you for more guesses) :


myguess=86
guess=int(raw_input("Guess a number between 1 and 100 "))
if guess<myguess : print ("The number is too small")
elif guess>myguess :
     print("The number is too big")
else :
     print("You guessed it!")


Let's go through the code line by line. The first line:

myguess=86 

means assign ( which is the symbol "=" ) the value 86 to our variable "myguess". Or you can read it as myguess (our variable) equals 86.

A variable can be thought of as a container that will store information for us. Some other languages require you to declare or allocate the variable first before you can use it. You have to declare what type of information it will store .e.g. a number or a text. With Python, we don't have to declare the variable first before we use it. We just use it and it will assign a number or text type to the variable depending on the value that is first assigned to it.

The second line:

guess=int(raw_input("Guess a number between 1 and 100 "))

means assign the value of int(raw_input("Guess a number between 1 and 100 ")) to the variable called "guess" . That's similar to the first line of our code, however, the difference is the value is not hard coded in the program, but rather the value comes from the input by the user.

We can see that the value is really the result returned by the function that we are calling. In this case, it is really two functions. The first function int (string parameter) is a function that interprets the string parameter (passed to it in parentheses) to a number ( int is short for integer i.e. not fractions or decimal points). This is a useful function because we want to accept input from the user to enter a number between 1 and 100. The function we used to do this is called raw_input . Raw inputs assumes that anything typed in by the user is of the type text, therefore it can literally accept almost anything the user types in without getting an error. In this case, if we type in "25", it doesn't know that it is the number 25. It only sees the binary representation of the character 2 and 5. By passing the user's input to the int () function, and making sure we pass in numerical characters only, the int() function can interpret or convert that "string number" into a number that it actually represented. i.e. "25" is converted to 25 by int(). "25" is a literal string and is not seen as a number. The int() function returns the interpreted value which can either be used directly or be assigned to a variable.

We've nested the raw_input () function into the int () function so that when Python executes the expression, it runs it in order from left to right. So int () expects a value, which in this case is the result of raw_input, which is a function which can accept a parameter or not. When a parameter is specified, it is displayed on the screen, and then it waits for user input. Once the user hits the Enter key, the function returns the string that was typed in, and returns that value, which in this case it returns it to the int() function. The third line and subsequent section checks for a particular condition and depending on the result redirects the program flow to execute the appropriate statements :

if guess<myguess : print ("The number is too small")
elif guess>myguess :
     print("The number is too big")
else :
     print("You guessed it!")

As the word "if" implies, if the condition or expression "guess < myguess" is true or correct i.e. the value of guess is less than ( "<" symbol means less than ) myguess, then execute any statements after the adjacent ":" symbol. This means that if guess was given the value of 50 , then :

 print ("The number is too small")

would be executed. NOTE: Since we only have one statement to execute for the true condition, we were able to put that single statement (print ....etc.. ) on the same line as the if statement after the ":" symbol.

If we had more than one statement to execute, for example, we have a statement that says "Try Again!", then we would have to move the "print" statement to the next line and indent it, and add any other statements that are part of that true condition :


if guess<myguess : 
     print ("The number is too small")
     print ("Try Again !")
elif guess>myguess :
     print("The number is too big")
else :
     print("You guessed it!")




Once the statements for the true condition is executed, the program exits the "if" statement. It will ignore the "elif" and "else" sections.

If however, the if condition was false, it will skip the statements in the "true" section and execute the next statement with the same indent as the "if" statement. This next statement happens to be "elif" which tells Python that this statement is a continuation of the first"if" statement. We could have not added the "elif" or "else" sections altogether and just put in print ("Get on with your life !") . All it means is this print statement will be executed regardless of what happens with the "if" condition because it is not a part of the "if" statement. However, it still needs to be on the same indent as the "if" statement.

"elif" is short for "else if" and like the "if" statement, will try to determine whether it's own condition or expression is true or false when it gets executed. It will behave the same way as a normal "if" statement. Which means if the condition is true, it's statements are executed and the program will exit the "if" statement.

"else" is like a catch all. If none of the "if" and "elif" conditions are true, the statements in the "else" section are executed and the "if" statement is exited. For our example, if guess is not less than or bigger than myguess, then it must be the same value!



The "for" Statement

If you have been running the example above, you will now be getting bored of having to Run the program each time.

So what if we want to make this program give us 10 tries ?

We can use the for/else control structure to do just that.

So let's modify our program to include the for/else structure.

Firstly, the syntax of the for/else control is:

for variable in expression :
     statements….
     statements….
[else :
     statements….
     statements….]

The [else : ... ] is optional.


Type in and run the following :

number_of_repeats = [0,1,2,3,4,5,6,7,8,9]
myguess=86
for i in number_of_repeats:
     guess=int(raw_input("Guess a number between 1 and 100 "))
     if guess<myguess :
          print ("The number is too small")
     elif guess>myguess :
          print("The number is too big")
     else:
          print("You guessed it!")


We basically created an array called number_of_repeats and initialised it with 10 elements.

The For command above repeats the block of code after the "For :" statement the same number of times as there are elements initialised for the array variable number_of_repeats i.e. 10.

OK. So that will repeat that section of code10 times for us. If we were to use the same technique to repeat this 100 times, it would be rather inefficient to do [0,1,3,4,5,6,etc…99] . Luckily for us, there is a range() function which we could use instead of an array.

So we can re-write the above example with the equivalent below:


myguess=86
for i in range(0,10):
     guess=int(raw_input("Guess a number between 1 and 100 "))
     if guess<myguess :
          print ("The number is too small")
     elif guess>myguess :
          print("The number is too big")
     else:
          print("You guessed it!")


The range() Function

The range() function, when called, returns a sequence of integer numbers depending on the parameter passed to it.

It's format is range([starting value,] stopping value [, incremental value])


The values in the [ ] brackets are optional.

An example of the parameters and the returned result is below. You can type in the examples below in the Python shell at the >>> prompt :

>>> range(10)

The result is :

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>

>>> range(4, 15)

The result is :

[4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>>

>>> range(4, 15, 2)

The result is :

[4, 6, 8, 10, 12, 14]
>>>

>>> range(4, -15, -2)

The result is :

[4, 2, 0, -2, -4, -6, -8, -10, -12, -14]
>>>

When it is used in a for loop, the number of times the loop is repeated is the same as how many items in the list that were returned. With each loop, the variable that is used in the for loop is assigned a value corresponding to the number in the list returned e.g. :

>>> for n in range (4, -15, -2) : print (n)
(then hit Enter twice)

The result is :

4
2
0
-2
-4
-6
-8
-10
-12
-14
>>>

Indentation Matters

To demonstrate the importance of indentation in the Python code, we will use the above example and not indent a particular line.

Original Code:

myguess=86
for i in range(0,10):
     guess=int(raw_input("Guess a number between 1 and 100 "))
     if guess<myguess :
          print ("The number is too small")
     elif guess>myguess :
          print("The number is too big")
     else:
          print("You guessed it!")


Modified Code with "incorrect" indentation:

myguess=86
for i in range(0,10):
     guess=int(raw_input("Guess a number between 1 and 100 "))
if guess<myguess :
     print ("The number is too small")
elif guess>myguess :
     print("The number is too big")
else:
     print("You guessed it!")




If we run the modified code, we will see that the program is going to be repeatedly asking us to guess a number between 1 and 100 for ten times, instead of asking once, and then checking if the number is smaller than or greater than the preset myguess value, and then asking us to guess again and repeating the whole process and only stopping after it's asked us ten times.


The "break" statement in loops

The break statement breaks out of the smallest enclosing for or while loop .

In our example with the guess the number program, we can see from the code that if we have guessed the correct number, the program will still loop the same number of times as there are number of items returned. So had we guessed the correct number the first try, it will still ask for us to guess the number until the for loop has finished processing.

>>> 
Guess a number between 1 and 100 86
You guessed it!
Guess a number between 1 and 100 86
You guessed it!
Guess a number between 1 and 100 7
The number is too small
Guess a number between 1 and 100 7
The number is too small
Guess a number between 1 and 100 7
The number is too small
Guess a number between 1 and 100 7
The number is too small
Guess a number between 1 and 100 7
The number is too small
Guess a number between 1 and 100 7
The number is too small
Guess a number between 1 and 100 7
The number is too small
Guess a number between 1 and 100 7
The number is too small
>>>


What we need to do to our program is to put the break statement in the part of the for loop section which gets executed when the guess is correct.

The code will now look like this :

myguess=86
for i in range(0,10):
     guess=int(raw_input("Guess a number between 1 and 100 "))
     if guess<myguess :
          print ("The number is too small")
     elif guess>myguess :
          print("The number is too big")
     else:
          print("You guessed it!")
          break


When you run the program and enter the correct guess the first time, it will now just exit the program.

>>> 
Guess a number between 1 and 100 86
You guessed it!
>>>


While this is fantastic that the program works like it should now, I was taught many years ago that a program should elegantly exit any loops or section. By elegantly I mean that if the program is in a loop, then the program should exit the loop when the loop condition becomes false or if it reaches the end of the programmed or calculated number of iterations.

If you find that you are relying heavily on break statements then it may mean that you have not sit down and design your program structure properly. For example, we can avoid having to put the break statement in for our guessing program by using the while loop instead of the for loop.



The "continue" Statement in Loops

The continue statement moves to the next iteration of the smallest enclosing for or while loop rather than exiting it completely.

This is not something that you should expect to see in common practise, but let's assume that the above guessing program was not designed properly. To achieve the same result, we may have had to write it like below :

myguess=86
for i in range(0,10):
     guess=int(raw_input("Guess a number between 1 and 100 "))
     if guess<myguess :
          print ("The number is too small")
          continue
     if guess>myguess :
          print("The number is too big")
          continue
     print("You guessed it!")
     break


That worked just like when we had the elif and else statements. So why don't we write the program this way? The reason is for readability and debugging purposes. If you are trying to find a bug, it is easier when we know that the loop condition itself controls the program flow. When we put the break and continue statements in, then each section has a potential to be the exit point.


The "while" Statement

The while statement is used to execute sets of statements while the condition or expression that is being tested is true.

We will alter the previous guessing program to demonstrate the while statement. Instead of using the for statement and repeat the question a set number of times, we will use a while statement which will ask the question until the guess is correct.

The syntax of the while statement is :

while condition or expession :
     statements....
     statements....
[else :
     statements....
     statements.... ]


Modified guessing program with the while statement :

myguess=86
guess=int(raw_input("Guess a number between 1 and 100 "))
while guess <> myguess:  
     if guess < myguess :  
          print ("The number is too small")  
     elif guess > myguess :  
          print("The number is too big")
     guess=int(raw_input("Guess a number between 1 and 100 "))
else: 
 print("You guessed it!")


Python Keywords and Built-in Functions

The following lists the built-in Python keywords. They are reserved words which means you cannot use them as a name for a variable or a function. Think of them as the ABCs of the Python language. However, you will need to use some of these built-in keywords with other built-in functions that have been created and distributed with Python to get any meaningful programs to be written. The power is then in the many functions that are distributed with Python and also from libraries that were written to extend Python. As an example, to program a nice GUI interface rather than just plain text output, you can use sets of functions distributed in the PyQT library, or it's alternative, PySide. This means the core Python language remains the same, and anything extra can all be learned as a separate topic or specialisation.

I will not go through the keywords and the built-in functions. There is enough documentation on them in the Python Documentation. From the Python IDLE development program, you can choose the Python Docs from the Help menu. You can find references on the keywords and the built-in functions. The way you should utilise the documentation is just have a browse through it so you get an idea what is in there. It should be used as a reference meaning you should start off with an idea for your program. You should be able to divide it into what are the inputs, outputs and processing required. Then you can see what keywords or functions will help you achieve your aim. Most of the time, the names of the keywords and the functions gives an idea of what that keyword or function does.

But I don't expect the beginner to be good at doing this straight away. It will become easier with more time doing coding and experimenting.

Keywords

and       del       from      not       while
as        elif      global    or        with
assert    else      if        pass      yield
break     except    import    print
class     exec      in        raise
continue  finally   is        return
def       for       lambda    try



Built-in Functions

abs()         divmod()    input()      open()      staticmethod()
all()         enumerate() int()        ord()       str()
any()         eval()      isinstance() pow()       sum()
basestring()  execfile()  issubclass() print()     super()
bin()         file()      iter()       property()  tuple()
bool()        filter()    len()        range()     type()
bytearray()   float()     list()       raw_input() unichr()
callable()    format()    locals()     reduce()    unicode()
chr()         frozenset() long()       reload()    vars()
classmethod() getattr()   map()        repr()      xrange()
cmp()         globals()   max()        reversed()  zip()
compile()     hasattr()   memoryview() round()     __import__()
complex()     hash()      min()        set()           
delattr()     help()      next()       setattr()        
dict()        hex()       object()     slice()           
dir()         id()        oct()        sorted()

Some Comparison Symbols and Meaning

The following are comparison operators or symbols which are used in the Python language. It is commonly used in the if/for/while conditions, but it is used for integer and string comparisons.

<

means less than. Example: if a < b . If a is less than b, then the condition is true, else condition is false.

>

means greater than. Example: if a > b . If a is greater than b, the the 
condition is true, else condition is false.

<>

means not equal to. Example: if a <> b . If a is not equal to be, then the 
condition is true, else condition is false.

==

means equal to. Example: if a == b . If a is equal to b, then the condition is 
true, else condition is false.

Python Data Types

The "type" of data determines what operations can be performed on that information and how it is stored in memory.

Usually a variable that is to be used needs to be declared a particular data type e.g. integer, string, etc.. We don't have to declare in Python as Python will automatically assign the appropriate data type to the variable when it first uses it.

In Python, data types take the form of objects. An example of Python's common Built-in objects (data types) are:

int, long, float, complex, str, byte, byte array, list, tuple, set, frozen set, dict.


We will look at the built-in data types in the next tutorial.


Summary

This tutorial provides a very simple introduction to the Python language and program flow control.

In the next tutorial, we will go through the built-in Python data types.

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.