''' Purpose: demonstrate the power of looping Four examples - without looping - loop over the characters in a string - loop over a list of words - loop over a range of integers ''' import pause # print the letters in a user-specified string of length 5 reply = input( 'Enter a five character long string: ' ) c0 = reply[ 0 ] c1 = reply[ 1 ] c2 = reply[ 2 ] c3 = reply[ 3 ] c4 = reply[ 4 ] print( c0 ) print( c1 ) print( c2 ) print( c3 ) print( c4 ) pause.enter_when_ready() # but what if the user wants a string may or may not have length five? # problem - we don't know how many assignment and print() statements # to supply # # remedy: use a Python for loop to manipulate the characters in a string # one by one reply = input( 'Enter a string: ' ) for character in reply : # character is called the iterator variable. It # takes on in turn each character in string reply. # The value following keyword in must be a sequence. # Here reply is a string; i.e., a sequence of # characters. print( character ) # The actions to be taken in the loop must be # indented. The actions are called the body of the # loop. In this example, the body of the loop is # a single statement -- a print() statement. # The body of the loop is run once for each character # in reply. The process is called iteration. # there is nothing special about the use of variable # character as the iterator variable. Python does not # care what we name it -- it just requires it be a # variable. I used character as indicates to the # reader what is going on. pause.enter_when_ready() # the for loop can also iterate over a list. let's now get some text from # the user. reply = input( 'Enter text: ' ) text = reply.split() # text is now a list of strings print( text ) pause.enter_when_ready() # use for loop to iterate over the strings in text for string in text : # string is now the iterator variable and # the sequence to examine is the list text string = string.capitalize() # This statement is here just to show you print( string ) # that the body of loop can have more than # one statement. Variable string will take # on each element of text one at a time. For # of those values, the body of the loop is # executed. pause.enter_when_ready() # another handy sequence can be gotten using range. range can create a # sequence of integers. The basic form in specifying a range is # range( n1, n2 ), where n1 and n2 are both integers. range( n1, n2 ) # produces the sequence of integers -- n1, n1 + 1, n1 + 2, ... n2 - 1 # let's show a for loop making use of range. we will get the arguments # for the range from the user. reply = input( 'Enter two integers: ' ) n1, n2 = reply.split() n1, n2 = int( n1 ), int( n2 ) # for ranging - accumulating the sum of n1, n1 + 1, n1 + 2, ... n2 - 1. # we will print out partial sums along the way sum = 0 for i in range( n1, n2 ) : sum = sum + i print( sum )