 # Python How to Conditionals & Loops Pt 3 Welcome to Part 3 of my Python How to Program tutorial. If you haven’t seen the other tutorials, check them out first Python How to Program : Tools Needed and Python How to Program Data Types.

In this article, I’ll be covering Conditionals (IF and Conditional Expression) and Loops (FOR and WHILE). Once again Python does things a little differently from other languages. And, while Python doesn’t include a switch statement for performing Conditionals, I’ll show you how to create one as well.

The IF Statement

You use the if statement to perform one action if one thing is true, or any number of other actions, if something else is true. We use indentation to define that code that is executed, based on whether a condition is met. This is a basic if, else check:

a, b = 1, 0
if a > b:

print(“a is greater than b”)

else:

print(“b is greater than a”)

You may be saying, but what do we do if a equals b? We actually need to check for 3 conditions and not just 2. Then we would use else if, or as Python calls it elif:

if a > b:

print(“a is greater than b”)

elif b > a:

print(“b is greater than a”)

else:

print(“a is equal to b”)

Comparing Data

There are many ways to compare data in Python. Here I’ll list them for you:

• > : Greater Than
• < : Less Than
• >= : Greater Than or Equal To
• <= : Less Than or Equal To
• == : Equal To
• != : Not Equal To

It is important to know that you can combine conditional checks with logical operators, as I show here:

a, b = 1, 1
if (a > b) and (a != b):

print(“a is greater than b”)

elif (a < b) and (a != b):

print(“a is less than b”)

else:

print(“a equals b”)

In the above code, I demonstrate how to check whether a is greater than and not equal to be with the and logical operator. Here are the other logical operators:

• or : If either statement is true, a value of true is returned
• not: Reverses the logical result ( not(True) == False )

Making a Python Switch Statement

Most programming languages have a tool called switch, that allows you to perform specific actions when a single variable is equal to a specific value. Here is the format of a PHP switch system:

switch (\$variable_passed) {

case ‘value1′:

// Perform actions

break;

default:

// Perform actions

break;

Python doesn’t have a specific way to perform this action, but I’ll implement the same technique here in Python. I think that code should be as readable as possible. By this I mean, code should be understandable to even someone new to programming. While there are many clever ways to create a switch technique in Python. I find the direct route to be the best. Here it is:
if value == ‘a’:

functiona ()

elif value == ‘b’:

functionb ()

elif value == ‘c’:

functionc ()

else:

functiond ()

You could implement this through the use of embedding inline functions with lambda in a dictionary. If your confused, be happy that I provided the simple solution for implementing switch in Python. You’ll learn all about lambda in a later article.

The Conditional Expression

There is a shorthand way to perform conditionals in Python. It is referred to as the Conditional Expression. Here is an example:

x, y = 1, 0;
a = ‘y is less than x’ if (y < x) else ‘x is less than y’
print(a)

The second line is known as a Conditional Expression in Python. While you don’t need the brackets around the comparision “y < x”; I find them useful.

Loops

The While Loop

You use a While Loop to perform the same action over and over again as long as a condition is met. Here is an example:

x = 1
while (x < 10):

print(x)
x = x+1

This will print the numbers 1 through 9 to the screen. If I wanted 1 through 10, I would change the condition to <=.

If you decide that you want to print from 1 to 10, but not print the number 4, you could achieve that with the continue statement. When the continue statement is triggered, all statements that follow are ignored and the loop is restarted. Here is an example:

x = 0
while (x < 10):

x = x+1
if x == 4 : continue
print(x)

Here is the Output:

1
2
3
5
6
7
8
9
10

When x equals 4, the print statement is skipped and that is why it is not shown in the output. There is another statement called break. When it is executed, your jumped completely out of the loop all together. If I would replace continue with break above, only 1 through 3 would have been printed on the screen.

The For Loop

The other way to loop in Python, is with the For Loop. Here is some example code:

x = “Some Random Words”
for y in x:

print(y)

This code will print each character in the string x on separate lines. We created an iterator called c. An iterator is just a temporary storage area. For the while loop above, the iterator was the variable x. In this for loop example we are temporarily storing the next character in the string in the iterator.

You can loop through pretty much any type of data structure with the for loop. You could also iterate through a series of numbers, like I show in the following example:

for x in [1, 2, 3, 4]:

print(x)

This would just print the numbers 1 through 4 to the screen. But, what if you want to iterate through a long list of numbers. Say you want to iterate from 1 to 200. Here I’ll show you how to iterate from 1 to 200 using a list and the range function:

listIterator = [1,2,3,4,5] # Note on how to create a small list
listIterator[:] = range(1,201) # Creating a list from 1 to 201
for i in listIterator: print(i) # Will print the numbers 1 to 200 on the screen

It’s worth noting that when you define the range of numbers to add to the list, make sure you add one like I did above. So if I wanted to create a range of numbers from 1 to 300, I’d use this range function listIterator[:] = range(1,301).

That’s All Folks

That is it for now. The best way to really get this stuff in your head is to write your own programs. So sit down with Eclipse and write some code. If you have any questions leave them in the comment section below.

Till Next Time

Think Tank