Getting Started with Python
Written by Mike James   
Thursday, 01 March 2018
Article Index
Getting Started with Python
Control Statements
Objects
Inheritance

Data structures

After discovering the basic variable types the next thing you should be interested in are the data structures that are available.

In Python there are no arrays but this doesn't matter because it has the list which can be used as if they were simple arrays.

Lists are in general more powerful and easier to use than arrays. You can create a list simply by writing constants within square brackets.

For example,

x=[1,2,3,4]

is a list of numbers.

The real power of a list is that it can contain any type of data including any Python objects and other lists. The items within a list can be of mixed type.

You can access list members using an index notation and you can insert and delete items in the same way.

For example, if

x=["spam","brian","grail"]

then x[0] is “spam” and

x[2] =“holy grail”

replaces the last item “grail” by “holy grail”.

Notice that, unlike other fundamental Python data types, the list is a “mutable” object, i.e. it can be changed without making a new copy.

In this mode of use lists look like arrays but they can be used in more sophisticated ways. There are functions which append to a list, sort it, reverse it count it and so on.

Of course, as already mentioned,  a list may contain a list and so you are free to build data structures which correspond to trees or anything else that can be made of nested lists - i.e. everything.

There are also some more advanced or specialized data structures that you need to be aware are available for use.

A special type of list, the tuple, is also supported and you can think of this as a generalisation of a co-ordinate pair such as (2,3).

Even more sophisticated is the dictionary, which you can think of as an associative array – that is you can look things up using non-numeric keys. For example:

x={"meat":"spam",0:"brian","holy":6}

and x[0] is "brian" and x["meat"] is "spam". Both keys and values can be strings or numeric.

Programs In IDLE

You can continue to "program" by typing lines into IDLE and having them executed at once but sooner or later you are going to have to construct a multiline program which you edit, save and only then attempt to execute.

To do this you have to first create a new file - use the File, New command in the IDLE shell that you have been using so far. A new window opens and you can use this like a standard code editor. For example you can type in:

print("Hello")
print("World")

and select Run,run module or press F5. You have to save the program before it can run. In this case you will see Hello and World on two separate line in the IDLE Shell.

run

This is how to run programs from now on.

Control structures

You need to know what sort of control structures are available in Python before moving on to consider the object-oriented nature of the language. Indeed, discovering how to form a conditional and various loops is part of learning any language.

As you would expect there are for and while loops and a full block structured if statement.

The only slight surprise is that the for loop enumerates through a list rather than numeric values. There is no C or Java style for loop with start expression, end expression and in increment. Instead for loops iterate though the elements in a sequence. That is

So, for example:

for z in x :

steps through each value stored in the list x.

To create a more traditional numeric for loop you can make use of the “range(n)” function which returns a list which runs from 0 to n-1. For example:

for z in range(10) :

repeats for values of z from 0 to 9.

Space Matters

The for loop is a compound statement header and this brings us to the subject of multi-line statements and blocks.

You need to pay special attention here because this is something that Python does differently from most other languages. 

Other languages use brackets like {} to group instructions into a block that are treated as one entity. Often these entities are also indented in control structures to show where they start and end. For example in C/Java like languages you would write something like:

for(z=0;z<10;z++){
    print("z=");
    print(z);
}

In this case the curly brackets indicate the the repeated block of statements includes both print commands i.e. they form the body of the loop.

Notice that the statements in the body of the loop have been indented and this is good programming practice but not mandatory.

In Python the indentation is used to identify the block and it isn't optional.  

For example –
x=["spam","brian","grail"]
for z in x:
    print(z)

which produces:

spam
brian
grail

The body of the loop is just the print statement and the indent is supplied automatically when you enter the : and press return.

In Python layout can change the meaning of a program.

If you manually enter indents using tabs or spaces then you determine the block that a statement belongs to.

For example if you type in

for z in x:
print ( z )

that is without a indent then the result is an error message as the for loop doesn't have a block to execute. The print(z) is the next instruction after the for loop. This is clearer to see in:

for z in x:
      print("z=")
      print(z)
print("loop finished")

In this case the body of the loop consists of the first two print statements and the third is outside of the loop and is executed when the loop ends.

The use of indents to give meaning to code is one of Python's most controversial features.

It has the advantage that good layout is essential to the working of the program. But if you need to change the structure of the program it can be more difficult than using curly brackets to mark blocks.

For example to include the for loop in another for loop you have to increase the indent of every line by one. This is made easier by the right tools but the fact still remains that sometimes you have to take the global structure of a program's text into account.

Tabs or spaces?

This is a universal question. Do you create an indent using tabs or spaces? You might be surprised to discover that Python prefers spaces. You can use tabs if you want to but in Python 3 you cannot mix using tabs and spaces even if they produce the same indent.

Conditionals And Indenting

Where indents often become confusing or an issue is in conditionals or IF statements.

For example

if x==1:
  print( "block 1")
  y=2
  if y==2:
    print( "block2")
  print ("block 1")
print("Ifs complete")

You can see that this way of entering blocks of code seems strange at first but you very quickly get used to it and it has many advantages.

Notice that the if statement has now been introduced and the symbol for a logical test of equality is “==”.

Which “if” an “else” statement pairs with is controlled by indenting. For example:

if x==1:
   print( "block 1" )
   y=2
   if y==2:
      print( "block 2" )
   else:
      print( "block 3" )
   print( "block 1" )

In this case the else pairs with the inner if statement which should be compared to:

if x==1:
   print( "block 1" )
   y=2
   if y==2:
     print( "block 2" )
else:
   print( "block 3" )
   print( "block 3" )

In the above snippet the else pairs with the outer if and both print statements are in the else block.

Always remember that it is the number of indents that define which block a line belongs to. Any set of consecutive lines with the same  indent forms a single block.

Another difference between Python and other languages is that the “else” can be paired with “for” and “while” as well as “if”. In this case the “else” is executed if the loop is exited normally, i.e. a break isn’t used to end it.

There is more to learn about Python control structures but this brief look is enough to get you started and certainly enough to let you read the rest of the code examples.



Last Updated ( Friday, 13 November 2020 )