Welcome to my Practical Python Programming post, hopefully this will be the first of many. If you have been following my ‘An Introduction to Python Programming’ posts series, then you may already know that in this post we are going to be having some fun. We are going to be creating a text based ‘Guess the Number’ game. All of the knowledge needed to create this game is contained in the ‘An Introduction to Python Programming’ posts, so as long as you have read those you should be able to follow this with relatively ease.
Welcome to my forth Python Programming introduction post. In this post we are going to be looking at lists and random numbers.If you have used another programming language before, then you have probably heard of an array, well, a python list is just an array, and in the same way you can have multi dimensional lists just as you can have multidimensional arrays.
Welcome to my third Python programming introduction post. In post #2 we looked at the basics of flow control using conditional statements. In this post we will be taking a look at another fundamental aspect of flow control; loops. A loop is a way of running a particular block of code more than once based upon a conditional. For example, we could have a loop ask a user for input continuously until they input “Exit”. That may not seem very useful but its just an example, loops are an extremely useful tool and definitely should not be overlooked. The two types of loops that we will be looking at are the
for loop and the
First off, the
for loop. The for loop is usually used for iterating a particular number of times. The usual first demonstration of a python for loop uses the
range(number) function. The range function when run outside of a loop returns a list object containing (depending on the arguments given) numbers from (unless stated otherwise) 0 through to
number. So, lets take a look at a for loop in action. In the following code we will be printing out the numbers 1 through to 100.
j = 1 for i in range(100): print j j += 1
This will print out, on separate lines, the numbers 1 through to 100. Lets pick this code apart. Firstly we have the variable declaration, pretty simple. The next line is the loop, and this is the slightly confusing part.
for i in range(100)
What this means is, for every object in the list, assign that object to the variable i, then iterate over the following code block. After the code block is complete, the next object in the list is assigned to the variable i and the code block is run again. This process is repeated untill there are no more objects in the list, thus it iterates 100 times. The next 2 lines are the code block.
print j j += 1
This should make sense, first print the variable
j then increase
j by 1. Hopefully this makes a bit of sense, if it doesn’t, don’t fret, play around a bit, try different numbers and variables.
Next we are going to be taking a look at the
while loop. The
while loop, unlike the for loop, will iterate continuously until its condition is met. This type of loop often causes problems for new programmers because it can easily be used to create infinite loops, loops where its conditional will never be met, we will look at an infinite loop after we have looked at a basic implementation of a
while loop, below is an example of a while loop performing the same task as our previous for loop
i = 1 while i != 101: print i i += 1
As you can see, there is not much difference. The main difference is in the line
while i != 101 what this means is that while the variable
i does not equal 101, print the variable then increase it by 1. Now, as promised, lets take a quick look at a slight variation of this loop, an infinite loop.
i = 1 while i != 101: print i
That will continuously print
1 until stopped by the user. Another, more interesting infinite loop would be this
i = 1 while True: print i i += 1
This loop will continuously print the variable
i incrementing it by 1 each time. The reason this loop is infinite is because the loops conditional is
True which is what a positive conditional returns, thus, an infinite loop.
Infinite loops are not all bad, there are many very valid reasons for using them, but be careful. In some compiled languages your program will segfault when you write an infinite loop.
I hope this post has helped you in your journey to becoming a python programmer. I will continue to write more introductory posts. Also, look out for my upcoming ‘Practical Python Programming Post’ which will be taking a more advanced approach (Suitable for beginner > intermediate programmers) looking at how python can be useful in everyday Ubuntu life.
Thanks for reading,
Welcome to my second python programming post. In the first post we looked at the
raw_input() function. We also looked at basic variable declaration and useage. In this post we will be taking a look at some more variables and also some basic flow control; flow control is the art of controlling your program based upon rules and conditionals. For example, a program that just has statements and funtions but no flow control will probably be pretty boring; both to write and to use, whereas a program that is correctly controlled can not only be a lot more useful for the user but also they can be extremely fun to write.
So without further ado, lets begin with multiple variable declaration. What this is, is declaring more then one variable in one statement/line. If we wanted to declare 3 variables in the way we learned in my first post, we would be doing something similar to this
var1 = "foo" var2 = "bar" var3 = "ubuntu"
Now, this is all well and good, but it unnecesarily uses 3 lines. We could instead, declare all of these variables together by doing the following.
var1, var2, var3 = "foo", "bar", "ubuntu"
as you can see, by doing things this wy, we have eliminated 2
= signs and 2 carriage returns, meaning we are only using 1 line.
Now, there are a few reasons why you wouldnt use this sort of variable declaration. First off, it is unlikely that at the beginning of writing your program you are going to know every variable that you will need. Secondly there is the issue of global and local variable scopes but we wont go into that now.
The next thing we are going to look at is flow control, in the form of the
if, elif, else statements. These ataements are the building blocks of almost every program and we shall take a look why this is so. Consider the following, A user enters his/her age into your program, you wish to output a line wich; depending on the age, says “Wow, your old!” or “Your very young” or “Nice middle age”. To do this we would use the
if, elif, else statements. Lets take a look at each one. The
if statement is the first statement you use, usually the
if statement is used to compare two or more values for equality, returning “True” for an equal comparison or “False” for a non-equal comparison. If the statement returns “True” then it runs a block of code, if it does not return “True” then it will then check for an
elif statements are run before
else statements and after
Now, before I talk about how to implement conditional statements I need to quickly mention syntax. Python is extremely sensitive to what is known as
whitespace, whitespace is, as you probably expected, spaces, tabs and carriage returns. In python code blocks such as those to be run upon a successful conditional comparison, are seperated from the rest of the code by indentation. If you get the indentation wrong on a block of code, when you come to run the program you will be presented with a syntax error. Usually, indentation should be either 4 spaces, or 8. Although the debate on which is better is an ongoing heated discussion but in general either is fine. The one thing both sides agree on is that indentation should never be created via tabs because a lot of people use different sizes of tabs and if you accidently mix tabs and spaces then someone else who tries to edit and run your code could be riddled with syntax errors.
So, now we have the formalities out of the way lets take a look at the implementation of conditional statements. The following code prompts the user for their name, age and sex. It then prints out a specific message dependant on the users entry.
name = raw_input("What is your name?: ") age = raw_input("How old are you?: ") sex = raw_input("Are you male (m) or female (f)?: ") if sex == 'm': print "Hello %s, you are a %s year old %s. Thats a good manly name." % (name, age, sex) elif sex == 'f': print "Hello %s, you are a %s year old %s. You have a very feminine name." % (name, age, sex) else: print "Hmm, thats odd, it seems", name, "you failed to enter 'm' or 'f'."
Now, lets take a look at this code. The first 3 lines just take user input as discussed in my first post. The next section, the
if clause checks for comparison between the variable
sex and the string ‘m’. If this comparison returns “True” then the string beneath the statement will be printed, the ‘%s’ signs in the string corraspond to the variable names in the tuple at the end of the line. If the comparison returns “False” then the
elif clause is checked, same as before, if “True” it runs its code block, if “False” it runs the
So, to wind up, your program should look like the following.
#! /usr/bin/env python name = raw_input("What is your name?: ") age = raw_input("How old are you?: ") sex = raw_input("Are you male (m) or female (f)?: ") if sex == 'm': print "Hello %s, you are a %s year old %s. Thats a good manly name." % (name, age, sex) elif sex == 'f': print "Hello %s, you are a %s year old %s. You have a very feminine name." % (name, age, sex) else: print "Hmm, thats odd, it seems", name, "you failed to enter 'm' or 'f'."
I hope this post has been informative for you, and I want to thank you for reading. To finish I would like to offer you a challenge. With your new knowledge, create a program that prompts the user for 2 of their friends name, age and sex and prints out the same information as we have done in our program here. For extra brwnie points collect al the information, then use a single print statement to print out all the information. A few hints for you would be use “\n” in your print statement to enter a new line, and also use variables in conjunction with the conditionals instead of print statements to store the strings first.
Python is a high level programming language useful for, but not limited to, everyday tasks. Python is quick to pick up and easy to understand. Many of python’s statements are very English like so there is not much confusion. Lets take a look at pythons basic print statement, we are going to be writing the traditional Hello World program first, and then we will take a look at some other things.
First off, you will need to install python. Using your preferred method of installation install the package
python. Now fire up your favourite editor and lets get started.
Now, the obligatory Hello World program just prints the words
Hello, World! to stdout which is usually the terminal.
To print to stdout python uses a
a string is just a bunch of characters. Now, to be able to run python programs directly you need to tell the computer what type of program you have written. We do this using what is called a ‘shebang’ line, named because the first two characters of the shebang line are
#! the shebang line for a python program looks like this
#! /usr/bin/env python
this tells the computer where the interpreter for your program, is stored. Go ahead and add that as the first line in your file. From this point on and in any subsequent python tuts I write here, I will assume that the shebang line has already been entered.
Now we get to the business part of our first program, the
print "Hello, World!"
Thats it, its that simple. Go ahead and add that line to your file, on a seperate line from the shebang line. Now save the file as “hello.py” (remember this is case sensitive) then, in the terminal, cd to the directory where you saved the file and run this command
You should now see “Hello, World!” printed on the terminal, if you do, well done you have successfully written your first python program. If you dont see those words or if you get an error message, re read what I have written and see if you made a mistake, if you didnt just leave a comment with the error message and whatever was in your file and I’l try and help get it sorted.
Now that we have had a look at printing a few words to the screen, lets look at printing variables. A variable is like a container that stores whatever you tell it to. Lets rewrite our Hello World program to use a variable. When you need to make a variable in python you use the = operator to assign it a value like this
hello = "Hello, World!"
This stores the string “Hello, World!” in the variable
hello. Now we can simply reference the variable name without any quotes in our print statement and we will get the contents of the variable printed, so construct your print statement like so
Save the file under hello2.py and run it in the same way as you did before (using the new filename). With any luck you should see the same output as before which is great! Well done!
Now you may be thinking that using a variable has added an extra line to our program unnecessarily but all will become aparent by the end of this post. So we now know a bit about the print statement and variables, now lets look at user input using the
raw_input() function. This function takes user input and can store it in a variable for printing/operating on. The
raw_input() function takes the following syntax
variable = raw_input("Prompt to be displayed: ")
then, whatever the user enters gets stored in the variable. So lets rewrite out Hello World program to use this method of printing a string. Enter the following into a file named hello3.py
string = raw_input("Input a string please: ") print "Your input was: %s" % string
Now, allow me to quickly explain a few things about that print statement that we have not seen before. The %s means that we want a variable of type string to be entered at that location. After the end quote we tell python that we want to tell it about an interpolated variable by using the % on its own followed by the variable name that we want entered.
With a bit of luck, you should now have written your first 3 python programs. In my next few python posts il be talking about loops and conditionals which really help structure your programs. I hope this was helpful to you, thanks for reading.