Python 2.7: Conditional & Control Flows

Python supports:

  • Standard comparison operators: <, >, ==, !=, <=, >=.
  • Logical operators: and, or, not (not is evaluated first, then and and then or)

Conditional Clause

if [condition]:
    [statements ...]
    [statements ...]

More sofisticated example, would be:

if [condition 1]:
    [statements ...]
elif [condition 2]:
    [statements ...]
    [statements ...]

Beware of the indentation as it will indicate how many statements to be executed within the condition success block. Example:

x_int = 12
if not x_int > 20:
    print "The value of our variable is %s" % x_int
    print "We used an if condition here"

Function Definition

Function can be defined using the following syntax:

def [function name]():
    [statements ... ]

Example of function definition:

# function defintion - notice the indentation defining the scope
def get_user_input(x_int):
    if x_int % 2 == 0:
        print "You've got an even number"
        print "You've got an odd number"

# obtaining raw input represented as string
x_string = raw_input("Type your number: ")
# converting the string to integer
x_int = int(x_string)

# calling the above defined function