Follow me on Twitter RSS FEED

Python Tutorial 3: Loops and Conditionals

Like I said in my First Python Tutorial, there are no brackets [ { and } ] ; Python uses indentation instead.

    a = 0
    while a < 10:
        a = a + 1
        print a
    print "End of loop"

Everything after the while a < 10: statement that is indented is repeated until a is no longer smaller than 10. Everytime through the loop, a is incremented, and then printed. The output of this program:

1
2
3
4
5
6
7
8
9
10
End of loop

Notice that "End of loop" is only printed once. That is because it is not indented, and hence comes after the while loop ends. Here is the basic form for the while loop:


while {condition that the loop continues}:
    {what to do in the loop}
    {have it indented, usually for spaces}
{the code here is not looped}
{because it isn't indented}




The if statement is rather similar


if(condition)
    statements
else
    statements




This can be very useful for many things


if(enteredPassword == correctPassword)
    login()
else
    print "Incorrect password";

0 comments:

Post a Comment