Nested Loops and Functions

Example:
for i in range(5):
    for j in range(3):
        print "i = " + str(i), "j = " + str(j)

Output:
i = 0 j = 0
i = 0 j = 1
i = 0 j = 2
i = 1 j = 0
i = 1 j = 1
i = 1 j = 2
i = 2 j = 0
i = 2 j = 1
i = 2 j = 2
i = 3 j = 0
i = 3 j = 1
i = 3 j = 2
i = 4 j = 0
i = 4 j = 1
i = 4 j = 2


Example: A Python program that reads 10 strings from the user, and for each string, prints the number of times the letter "a" appears in the string.



Exercise: Write a python program that prints the following triangle, in which the first row contains 1 *, row 2 contains 2 *'s, ... and row 10 contains 10 *'s.
*
**
***
****
*****
******
*******
********
*********
**********

Note: One disadvantage of printing with print is that print always adds a blank space after each printed item. We can avoid this by using sys.stdout.write() from the sys library.

import sys
sys.stdout.write("hello")
sys.stdout.write("world")

Output: helloworld

Exercise: Write a python function printTriangle() that has a parameter for the number of rows in a triangle like the one in the last example. In the main function, read the number of rows from the user (and prompt the user for another value until the input is positive). Then call the printTriangle() function.


Exercise: Write a Python program that prints the following output. The triangle contains 10 rows. The first row contains 1 *, the second contains 2 *'s, etc.
                *
              **
            ***
...
**********


Functions with Parameters and Return Values

General form of a function definition:
def functionName(parm1, parm2, parm3):
    <code>
    <more code>
    return someValue


To call this function:
answer = functionName(arg1, arg2, arg3)

What happens when the function is called?
functionName is executed with:

Example:
def main():
    # run sumIt with small=2, large=4
    print sumIt(2, 4)
    # run sumIt with small = -1, large = 5
    print sumIt(-1, 5)

def sumIt(small, large):
    if small <= large:
        sum = 0
        for i in range(small, large+1):
            sum += i
    else:
        sum = 0
     return sum

main()  # execute main function




Exercise: Write a function called reverseIt that takes a string parameter and returns the reverse of the string. Write a main function that reads 10 strings from the user, and prints the reverse of each string.