Code

An Introduction to Python Programming #2

0

Welcome to my second python programming post. In the first post we looked at the print statement used to print to the screen, and we also looked at basic user input via 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 or else statement. elif statements are run before else statements and after if statements.

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 else clause.

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.

Happy coding!

Craig Soutar
My name is Craig Soutar. I am a computer enthusiast from the UK. I first started using Ubuntu in December of 2007, this was also my first Linux OS. I have since taught myself; with the help of the community documentation, IRC and forums, how to cope with everyday life on Ubuntu.
You may also like
php-tux
Easy PHP II: Variables
How-to-find-category-or-tag-ID-in-WordPress
How to find a WordPress category ID

Leave Your Comment

Your Comment*

Your Name*
Your Webpage