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.
After a long time using Windows, I switched to Ubuntu, but I noticed that my own sites and other daily ones like Gmail and different other blogs I read where not looking as good as they were before the switch. Being a web developer I know that web sites are designed with Microsoft fonts in mind and the CSS style-sheets specify those fonts. Those fonts are often referred to as web safe fonts. So, the Microsoft fonts that my eyes were used to looking at were missing. Those fonts do not come pre-installed in Ubuntu so we have to install them ourselves. However, in Ubuntu we are not restricted to have only those MS fonts we mentioned, we can add as many new fonts as we like and that is cool. Below we will be explaining the way that we can install Microsoft fonts and how to add new fonts too.
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.