Loops and Strings

We covered the following examples on the board:


Return the last 2 characters of a string:

def last2(s):
    return s[-2:]


Add up the cubes of the numbers from 1 to n:

def sum_cubes(n):
    counter = 1
    answer = 0
    while counter <= n:
        answer = answer + counter**3
        counter = counter + 1
    return answer


Return n duplicate copies of a string:

def dups(s,n):
    counter = 1
    answer = ''
    while counter <= n:
        answer = answer + s
        counter = counter + 1
    return answer


Count how many times a character appears in a string:

def ccount(s,c):
    counter = 0  # note that this starts at 0 instead of 1
    answer = 0
    while counter < len(s):  # note that this is a little different
        if s[counter] == c:
            answer = answer + 1
        counter = counter + 1
    return answer


Homework problems: Create a .py file with all of the functions below, plus your test cases, and submit to the homework server.

1. strcount(s,q).  returns how many times the string q appears in the string s.  Examples (look at these carefully and undrstand them before starting):


2. div23(n): Add up the numbers (from 1 to n) that are evenly devisible by 2 or evenly divisibly by 3 (or both).  Examples:


3. findchar(s,c): returns the position of the first occurrence of the character c in the string s (c will aways be a single character).  Returns -1 if not found.  Examples:


4. findstringrev(s,q): returns the position of the last occurrence of the string q in the string s.  Returns -1 if not found.  Examples: