Showing posts with label if. Show all posts
Showing posts with label if. Show all posts

Tuesday, 28 July 2015

Functions

#!/usr/bin/env python

# Functions allow us to include code in our programs that will only run when
# explicitly called and can be reused.

# Simple function example.
def allStars(n):
        for i in range(0,n):
                print "*"

# Main Program
run = True              
while run:
        x = raw_input("How many stars should I print? ")
        if str.isdigit(x):
                allStars(int(x))
                x = raw_input("Do you want another go? Press Y or N")
                if str.upper(x) == "N":
                        run = False
        else:
                print "%s is not a number." % x

Monday, 27 July 2015

Making Decisions: if-elif-else

#!/usr/bin/env python

# Programs normally execute one line after the other from top to bottom.
# But sometimes we need to make a decision while the program is running.
# Some of these decisions will send the program down one path or the other.

# To do this in Python we use the if-elif-else statements.

# The first thing to note is Python uses indentation to define code blocks
# rather than the {} notation found in C or Java. This means in Python
# indentation of code blocks is manditory. We also don't actually
# type "then" as in "if condition is true then do somemthing". Instead we use
# a colon ":". Because why not?

# Basic if statement.
A = 0 # Integer.
if A == 0: print A

# A more complex example with indentation defining a code block.

A = [1,2,3,4,5] # List of integers.
if A[0] != 0:
        print ("A at index 0 is equal to %d.") % A[0]
        print ("A at index 0 is equal to %d.") % A[1]
        print ("A at index 0 is equal to %d.") % A[2]
        print ("A at index 0 is equal to %d.") % A[3]
        print ("A at index 0 is equal to %d.") % A[4]      

# Both the examples above will only print the value of A if the condition is
# met. But often we need alternative actions to be taken when the condition
# has not been met. For this we add the else statement.

A = 1
if A == 0:
        print A
else:
        print ("A is not 0.")
       
# By adding additional if statements we can test for multiple possibilities.
# We do this in Python by using elif.

A = 2
if A == 0:
        print A
elif A == 1:
        print A
elif A == 2:
        print A
elif A == 3:
        print A
else:
        print ("The value of A does not match the test.")