Py-Tut-005

Back to Learning Python

Comparison Operators
Earlier we looked at some basic Mathematics operators. Now we will look at operators that compare two items
 * Less Than, "<"
 * Less Than or Equal To, "<="
 * Greater Than, ">"
 * Greater Than or Equal To, ">="
 * Equal To, "==" #Note there are two equal signs for comparison
 * Not Equal To, "!="

The "If" Statement
Often what we want to do depends upon something else. We may want to print one thing if something is true, but we may want to print something else if it is false.

A very important detail to note now is that of indenting. In Python, all blocks of code that execute together must be indented the same amount. The If statement introduces a new block of code and so must be indented together.

code format="python" userAge = int( raw_input('Please enter your age') ) If userAge < 16: print "You are not old enough to drive" code

The "Elif" and "Else" Statement
The "Elif" statement is short for saying "Else if". In this way we can further direct the flow of our program. The "Else" statement is a way of saying "for everything else, do this". Note you can have as many "Elif" statements after an "If" as you want, but there can only be one "Else" statement and it has to be at the end.

Note that a colon is required after each line of If, Elif, and Else.

code format="python" userAge = int( raw_input("Please enter your age: ") ) if userAge < 16: print "You are not old enough to drive" elif userAge < 18: print "You are old enough to drive but too young to vote" else: print "You are old enough to drive and vote."

code

Assignment 5
Write a program that asks the user to enter their name and two numbers. Print back their name and state which of the two entered numbers is larger.

Back to Learning Python