Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Python Masterclass

Name: Programmer 2013-08-03 14:23

Python Masterclass

Always wanted to have a go at programming? No more excuses, because Python is the perfect way to get started!

Python is a great programming language for both beginners and experts. It is designed with code readability in mind, making it an excellent choice for beginners who are still getting used to various programming concepts. The language is popular and has plenty of libraries available, allowing programmers to get a lot done with relatively little code.

   You can make all kinds of applications in Python: you could use the Pygame framework to write simple 2D games, you could use the GTK libraries to create a windowed application, or you could try something more ambitious like the app where we used Python's Bluetooth and input libraries to capture the input from a USB keyboard and relay the input events an Android phone.

   For this tutorial, we're going to be using Python 2.X.

Hello World

Let's get stuck in, and what better way than with the programmer's best friend, the 'Hello World' application! Start by opening a terminal. Its current working directory will be your home. It's probably a good idea to make a directory for the files we'll be creating in this tutorial, rather than having them loose in your home directory. You can create a directory called Python using the command mkdir Python. You'll then want to change into that directory using the command cd python.

   The next step is to create an empty file using the command 'touch' followed by the filename. Our expert used the command touch hello_world.py. The final and most important part of setting up the file is making it executable. This allows us to run code inside the hello_world.py file. We do this with the command chmod +x hello_world.py. Now that we have our file set up, we can go ahead and open it up in nano, or any text editor of your choice. Gedit is a great editor with syntax highlighting support that should be available on any distribution. You'll be able to install it using your package manager if you don't have it already.


[liam@liam-laptop -]$  mkdir Python

[liam@liam-laptop -]$  cd   Python/

[liam@liam-laptop  Python]$ touch  hello_world.py

[liam@liam-laptop  Python]$ chmod  +x  hello_ world.py

[liam@liam-laptop  Python]$ nano   hello_world.py


   Our Hello World program is very simple, it only needs two lines. The first line begins with a 'shebang' (the symbol #! - also known as a hashbang) following by the path to the Python interpreter. The program loader uses this line to work out what the rest of the lines need to be interpreted with. If you're running this in an IDE like IDLE, you don't necessarily need to do this.

   The code that is actually read by the Python interpreter is only a single line. We're passing the value Hello World to the print function by placing it in brackets immediately after we've called the print function. Hello World is enclosed in quotation marks to indicate that it is a literal value and should not be interpreted as source code. As expected, the print function in Python prints any value that gets passed to it to the console.

   You can save the changes you've made to the file in nano using the key combination Ctrl+O, followed by Enter. Use Ctrl+X to exit nano.

#!/usr/bin/env python2

print("Hello World")


   You can run the Hello World program by prefixing its filename with ./ - in this case you'd type ./hello_world.py.

[liam@liam-laptop  Python]$ ./hello_world.py

Hello World



Variables and data types

A variable is a name in source code that is associatd with an area in memory that you can use to store data, which is then called upon throughout the code. This data can be one of many types, including:

Integer : Stores whole numbers

Float : Stores decimal numbers

Boolean : Can have a value of True or False

String : Stores a collection of characters. "Hello World" is a string

As well as these main data types, there are sequence types (technically, a string is a sequence type but is so commonly used we've classed it as a main data type):

List : Contains a collection of data in a specific order

Tuple : Contains a collection immutable data in a specific order

A tuple would be used for something like a co-ordinate, containing an x and y value stored as a single variable, whereas a list is typically used to store larger collections. The data stored in a tuple is immutable because you an't change values of individual elements in a tuple. However, you can do so in a list.

   It will also be useful to know about Python's dictionary type. A dictionary is a mapped data type. It stores data in key-value pairs. This means that you access values stored in the dictionary using that value's corresponding key, which is different to how you would do it with a list. In a list, you would access an element of the list using that element's index (a number representing the element's position in the list).

   Let's work out a little program we can use to demonstrate how to use variables and different data types. It's worth noting at this point that you don't always have to specify data types in Python - it will generally work out the correct data type for you. Feel free to create this file in any editor you like. Everything will work out just fine as long as you remember to make the file executable. We're going to call ours variables.py.

Name: Programmer 2013-08-03 14:33

Continue

However, functions can also return values, so this isn't an issue. Functions are defined with keyword def, followed by the name of the function. Any variables that can be passed through are put in brackets following the function's name. Multiple variables are separated by commas. The names given to the variables in these brackets are the ones that they will have in the scope of the function, regardless of what the variable that's passed to the function is called . Let's see this in action.


#!/usr/bin/env python2

# Below is a function called modify_string, which accepts a variable

# that will be called original in the scope of the Function. Anything

# indented with 4 spaces under the function definition is in the

# scope.

def modify_string(original):

    original += " that has been modified."

    # At the moment, only the local copy of this string has been modified

def modify_string_return(original):

    original += " that has been modified. "

# However, we can return our local copy to the caller. The function

# ends as soon as the return statement is used, regardless of where it

# is in the function.

  return original

test_string = "This is a test string"  // We are now outside of the scope of the modify_string function, as we have reduced the level of indentation

modify_string(test_string)

print(test_string)  // The test string won't be changed in this code.

test_string = modify_string_return(test_string)

print(test_string)  //However, we can call the function like this

# The function's return value is stored in the variable test string,

# overwriting the original and therefore changing the value that is

# printed.



The output from the program opposite is as follows:


[liam@liam-laptop Python]$ ./functions_and_scope.py

This is a test string

This is a test string that has been modified.



   Scope is an important thing to get the hang of, otherwise it can get you into some bad habits. Let's write a quick program to demonstrate this. It's going to have a Boolean variable called cont, which will decide if a number will be assigned to a variable in an if statement. However, the variable hasn't been defined anywhere apart from in the scope of the if statement. We'll finish off by trying to print the variable.


#!/usr/bin/env python2

cont = False

if cont:

   var = 1234

print(var)



   In the code above, Python will convert the integer to a string before printing it. However, it's always a good idea to explicitly convert things to strings - especially when it comes to concatenating strings together. If you try to use the + operator on a string and an integer, there will be an error because it's not it's not explicitly clear what needs to happen. Having said that, Python's string formatter that we demonstrated earlier is a cleaner way of doing that. Can you see the problem? Var has only been defined in the scope of the if statement. This means that we get a very nasty error when we try to access var.


[liam@liam-laptop Python]$ ./scope.py

Traceback (most recent call last):

  File "./scope.py", line 8, in <module>

   print var

NameError: name 'var' is not defined



   If cont is set to True, then the variable will be created and we can access it just fine. However, this is a bad way to do things. The correct way is to initialise the variable outside of the scope of the if statement.


#!/usr/bin/env python2

var = 0

if cont:

   var = 1234

if var != 0:

print(var)



   The variable var is defined in a wider scope than the if statement, and can still be accessed by the if statement. Any changes made to var inside the if statement are changing the variable defined in the larger scope. This example doesn't really do anything useful apart from illustrate the potential problem, but the worst-case scenario has gone from the program crashing to printing a zero. Even that doesn't happen because we've added an extra construct to test the value of var before printing it.

Comparison operators

The common comparison operators available in Python include:

<  strictly less than

<= less than or equal

strictly greater than

>= greater than or equal

== equal

!= not equal


Coding style

It's worth taking a little time to talk about coding style. It's simple to write tidy code. The key is consistency. For example, you should always name your variables in the same manner. It doesn't matter if you want to use camelCase or use underscores as we have..

   One crucial thing is to use self-documenting identifiers for variables. You shouldn't have to guess what a variable does. The other thing that goes with this is to always comment your code. This will help anyone else who reads your code, and yourself in the future. It's also useful to put a brief summary at the top of a code file describing what the application does, or a part of the application if it's made up of multiple files.

Summary

This article should have introduced you to the basics of programming in Python. Hopefully you are getting used to the syntax, indentation and general look and feel of a Python program. The next step is to learn how to come up with a problem that you want to solve, and break it down into small enough steps that you can implement in a programming language.

   Google, or any other search engine, is very helpful. If you are struck with anything, or have an error message you can't work out how to fix, stick it into Google and you should be a lot closer to solving your problem. For example, if we Google 'play mp3 file with python', the first link takes us to a Stack Overflow thread with a bunch of useful replies. Don't be afraid to get struck in - the real fun of programming is solving problems one manageable chunk at a time.

Happy programming


Tip

If you were using a graphical editor such as gedit, then you would only have to do the last step of making the file executable. You should only have to mark the file as executable once. You can freely edit the file once it's executable.

Python has plenty of great on line documentation. Usually the best way to find things is to simply Google them and the first result will be the official Python documentation. For example, there is a very detailed page on Python's built-in types here: http://docs.python.org/2/library/stdtypes.html

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List