Monday, July 14, 2008

Second Python Fun Tutorial - Program Flow

This is the tutorial where we will start to write some, semi-useful programs! First though we need to learn some more ways to do things in python. To do this we need to write more than one line of code at a time. Open IDLE and go FILE>New Window.





You should now have a blank text window. The only thing different about writing it here is that there is multiple lines, can be saved, and run again without retyping! The only thing that the console(The first open window in python) is better at is for evaluating one or two line statements. Now to use this new windows put in something simple like:

print "Hello pythonfun.blogspot.com!, I love your tutorials!"

Then go to RUN>Run Module, or you can press F5.

You should get a window asking you to save it. I chose "Python Fun Tutorial2". You should see the console open back up with:

>>> ================================ RESTART ========================
>>>
Hello pythonfun.blogspot.com!, I love your tutorials!
>>>

The Restart line just means you ran a new script. And then you can see the line printed. Now we are going to look at some important statements. These are the IF, and WHILE statements. The if statement tests if something is true, and if the statement evaluated is true it will run the indented code. So try a program like this:



After running it you should get, "X is equal to 50". There are several things you need to notice here, the first is the colon. After every IF statement there needs to be a colon. The indentation, as long as code is indented, python will know that it is part of that IF statement. The third is the single equal mark when assigning variables, and the double equal marks when testing to see if they are true. There are several other operators that can be used in an if statement, they are:
Operator
Function
< less than
<= less that or equal to
> greater than
>= greater than or equal to
!= not equal to
== equal to



However it becomes very clear that we still need more control over this program. What if x was = 49? It would print both of the statements. Or 51? It would say that x is 50! This where we will use the elif statement, and the else statement. Try putting in:

x = 50
if x == 49:
print "X is equal to 49"
elif x == 50:
print "X is equal to 50"
else:
print "X is not equal to 49 or 50"

Elif only stands for Else If. So it can only be used after an IF statement. In python Elif will only be evaluated if the original IF statement was false. You can have as many Elif's after an if statement as you want. However you can only have one ELSE statement. Once again the ELSE statement will only be evalutated if all the preceding IF and ELIF statements are false.

1 comment:

Anonymous said...

Hey, Great Tutorial