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:24

Continue

Interpreted vs compiled languages

An interpreted language such as Python is one where the source code is converted to machine code and then executed each time the program runs. This is different from a compiled languages such as C, where the source code is only converted to machine code once - the resulting machine code is then executed each time the program runs.


#!/usr/bin/env python2


# We create a variable by writing the name of the variable we want followed

# by an equals sign, which is followed by the value we want to store in the

# variable. For example, the following line creates a variable called

# hello_str, containing the string Hello World.

hello_str "Hello World"

hello_int = 21  // The following line creates an integer variable called hello_int with the # value of 21. Notice how it doesn't need to go in quotation marks

hello_bool = True  // The same is true of Boolean values

hello_tuple = (21, 32)  // We create a tuple in the following way

hello_list = ["Hello,", "this", "is", "a", "list"]  // And a list in this way

# This list now contains 5 strings. Notice that there are no spaces

# between these strings so if you were to join them up so make a sentence

# you'd have to add a space between each element.

hello_list = list() 
hello_list.append("Hello,")
hello_list.append("this")
hello_list.append("is")
hello_list.append("a")
hello_list.append("list") // You could also create the same list in the following way

# The first line creates an empty list and the following lines use the append

# function of the list type to add elements to the list. This way of using a

# list isn't really very useful when working with strings you know of in

# advance, but it can be useful when working with dynamic data such as user

# input. This list will overwrite the first list without any warning as we

# are using the same variable name as the previous list.

hello_dict = { "first name" : "Liam",
               "last_name"  : "Fraser",
               "eye_colour" : "Blue" }  // We might as well create a dictionary while we're at it. Notice how we've aligned the colons below to make the code tidy

# Let's access some elements inside our collections

# We'll start by changing the value of the last string in our hello_list and

# add an exclamation mark to the end. The "list" string is the 5th element

# in the list. However, indexes in Python are zero-based, which means the

# first element has an index of 0.

print(hello_list[4])

hello_list[4] += "!"

# The above line is the same as

hello_list[4] = hello_list[4] + "!"

print(hello_list[4])  // Notice that there will now be two exclamation marks when we print the element

print(str(hello_tuple[0]))  // Remember that tuples are immutable, although we can access the elements of them like so

# We can't change the value of those elements like we just did with the list

# Notice the use of the str function above to explicitly convert the integer

# value inside the tuple to a string before printing it.

print(hello_dict["first_name"] + "" + hello_dict["last_name"] + " has " +
      hello_dict["eye_colour"] + " eyes.")  // Let's create a sentence using the data in our hello_dict

print("{0} {1} has {2} eyes.".format(hello_dict["first_name"],
                                     hello_dict["last_name"],
                                     hello_dict["eye_colour"]))  // A tidier way of doing this would be to use Python's string formatter



Tip

At this point, it's worth explaining that any text In a Python file that follows a # character Will be ignored by the interpreter. This is so you can write comments in your code.

More about a Python list

A Python list is similar to an array in other languages. A list (or tuple) in Python can contain data of multiple types, which is not usually the case with arrays in other languages. For this reason, we recommend that you only store data of the same type in a list. This should almost always be the case anyway due to the nature of the way data in a list would be processed.

Indentation in detail

As previously mentioned, the level of indentation dictates which statement a block of code belongs to. Indentation is mandatory in Python, whereas in other languages, sets of braces are used to organise code blocks. For this reason, it is essential that you use a consistent indentation style. Four spaces are typically in Python. You can use tabs, but tabs are not well defined, especially if you happen to open a file in more than one editor.

Name: Programmer 2013-08-03 14:27

Continue

Control structures

In programming, a control structure is any kind of statement that can change the path that the code execution takes. For example, a control structure that decided to end the program if a number was less than 5 would look something like this:


#!/usr/bin/env python2

import sys # Used for the sys.exit function

int_condition = 5

if int_condition < 6:
   
    sys.exit("int_condition must be >= 6")

else:

    print("int_condition was >= 6 - continuing")



   The path the code takes will depend on the value of the integer int_condition. The code in the 'if' block will only executed if the condition is true. The import statement is used to load the Python system library; the latter provides the exit function, allowing you to exit the program, printing an error message. Notice that indentation (in this case four spaces per indent) is used to indicate which statement a block of code belongs to.

   'if' statements are probably the most commonly used control structures. Other control structures include:

• For statements which allow you to iterate over items in collections, or to repeat a piece of code a certain number of times;

• While statements, a loop that continues while the condition is true.

   We're going to write a program that accepts user input from the user to demonstrate how control structures work. We're calling it construct.py.

   The 'for' loop is using a local copy of the current value, which means any changes inside the loop won't change the list. However, the 'while' loop is directly accessing elements in the list, so you could change the list there should you want to. We will talk more about variable scope later. The output from the above program is as follows:

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

How many integers? acd

You must enter an integer

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

How many integers? 3

Please enter integer 1: t

You must enter an integer

Please enter integer 1: 5

Please enter integer 2: 2

Please enter integer 3: 6

Using a for loop

5

2

6

Using a while loop

5

2

6

Name: Programmer 2013-08-03 14:29

Continue

Functions and variable scope

#!/usr/bin/env python2

# We're going to write a program that will ask the user to input an arbitrary

# number of integers, store them in a collection, and then demonstrate how the

#collection would be used with various control structures.

import sys # Used for the sys.exit function

target_int = raw_input("How many integers? ")  //The number of integers we want in the list

# By now, the variable target_int contains a string representation of

# whatever the user typed. We need to try and convert that to an integer

# be ready to # deal with the error if it's not. Otherwise the program

# crash.

try:

   target_int = int(target_int)

except ValueError:

   sys.exit("You must enter an integer")

ints = list()  // A list to store the integers

count = 0  // Used to keep track of how many integers we currently have

# Keep asking for an integer until we have the required number

while count < target_int:

   new_int = raw_input("Please enter integer {0}: ".format(count + 1 ))

   isint = False

   try:

        new_int = int(new_int)  // If the above succeeds then isint will be set to true: isint = True

   except:

        print("You must enter an integer")

# Only carry on if we have an integer. If not, we'll loop again

# Notice below I use ==, which is different from =. The single equals is an

# assignment operator whereas the double equals is a comparison operator.

if isint ==True:

  # Add the integer to the collection

   ints.append(new_int)

# Increment the count by 1

   count += 1

print("Using a for loop")

for value in ints:

   print(str(value))  // By now, the user has given up or we have a list filled with integers. We can loop through these in a couple of ways. The first is with a for loop

# Or with a while loop:

print("Using a while loop")

# We already have the total above, but knowing the len function is very

# useful.

total = len(ints)

count = 0

while count < total:

   print(str(ints[count]))

   count += 1


Tip

You can define defaults for variables if you want to be able to call the function without passing any variables through at all. You do this by putting an equals sign after the variable name. For example, you can do: def modify_string (original=" Default String")

Functions are used in programming to break processes down into smaller chunks. This often makes code much easier to read. Functions can also be reusable if designed in a certain way. Functions can also have variables passed to them. Variables in Python are always passed by value, which means that a copy of the variable is passed to the function that is only valid in the scope of the function. Any changes made to the original variable inside the function will be discarded.

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

Name: Anonymous 2013-08-08 4:30


#  kid strangler

strangle kid

Name: Anonymous 2013-08-09 15:34

What?! This isn't about gay, jew anusses being rampaged by niggers!

Imma outta here!

Name: Anonymous 2013-08-11 13:13

>>7

Good! And remember to get lost in twilight zone sucker!

Name: Anonymous 2013-09-07 1:18

>>5

The correct sentence is this :

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

Name: Anonymous 2013-09-07 1:21

What wrong? Why the > become into | in this board?

The correct sentence again :

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

Name: Anonymous 2013-09-07 1:23

REPOST AGAIN!

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

Name: Anonymous 2013-09-07 1:27

> strictly greater than

Name: Anonymous 2013-09-07 1:29

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

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