Python 2.7: Conditional & Control Flows
Hands-On | 04 Dec 2016
- Standard comparison operators: <, >, ==, !=, <=, >=.
- Logical operators: and, or, not (not is evaluated first, then and and then or)
if [condition]: [statements ...] else: [statements ...]
More sofisticated example, would be:
if [condition 1]: [statements ...] elif [condition 2]: [statements ...] else: [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 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" else: 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 get_user_input(x_int)