Reading For, While and If programs (i.e. nested iteration examples)

The first example we will review is an example of the use of loops nested within an IF statement. This program is interactive and will ask the user whether to print odd number or even numbers up to a maximum value.

ans = input('Do you want to print Odds or Evens')
max = int(input('How high do you want to go?')) # Note use of int() to convert the returned value
if ans=='Odds':
    while x <= max :
        print x,
        x = x+2
elif ans=='Evens' :
    while x <= max:
        print (x,end=" ")
        x = x + 2
    print ('You did not type in Odds or Evens')
    print ('Whats up with that?')

Hmmm . Could you rewrite the above program in a more compact way. i.e a small if then else followed by a single while. Hint: Determine the starting value of x only within the if and then follow that with a single while. Try it you will like it.

#This second problem is an if inside of a for loop. 
#Its job is to accumulate the evens and odds that occur
#in a list. The list is just a list of random integer values we type in.

for i in [1,2,5,4,6,8,7,9,11,22,43,21]:
  # % is an operator that means: divide and return the remainder.
 # just like you did in grammar school. eg 10%3 is 1
 # Its called the modulo operator
    if i%2==0:  # i is an even integer.
        sum_evens = sum_evens + i
    else:  # then we are odd
        sum_odds = sum_odds + i
print ('The sum of the evens is',sum_evens)
print ('The sum of the odds is',sum_odds)

#how would you change the above program so that it prints
#the average instead of the sums?

The following problem is a using a property of strings that resemble lists.  Strings act as a ‘list’ of characters so you can use a for command to traverse the characters of a string. Here we will look down the characters of a string , printing each character on the same line until we see a space.  At that point we print a CR.  While we are doing this we also count the number of characters printed on each line and display that value at the end of the line.

s='The Knights Who Say Ni demand a sacrifice!'
for i in s:
    if i==' ':
        print (ct)
    print (i,end=' ')

There is a major and a minor error in the above program.  What are they?  Is there some way we can fix them?  HOW?

Here is another loop inside of a loop.  What is printed?  What is printed if you swap the i and j in the two for statements.

print ('i  j')
for i in range(3):
    for j in range(2):
        print (i,j)
    print ("End of Inner Loop")

Play with the above changing range values etc.  Convert the above to three nested loops using i,j, and k.  Run it.

Check the following one out as well.

num = int(input('Number to sum to:'))
for i in range(num+1):
print ('The sum is',sum)
print ('The average is',sum/float(num))

What does the above calculate.   Why do I use an int in line 4?  Why do I use float in the last line?

Comments are closed.