[pythonvis] Some simple exercises for using loops

  • From: "Joseph Lee" <joseph.lee22590@xxxxxxxxx>
  • To: <pythonvis@xxxxxxxxxxxxx>
  • Date: Mon, 19 May 2014 12:16:39 -0700

Hi all,

It seems that we need some simple exercises that deals with loops, and some
who atteneded today's audio session felt that we might need to put off
Richard's puzzle for now (I personally feel that puzzle is something that
computer science students should solve).

As alternatives, here are some simple puzzles and hints on using loops:

1.      You have a list of numbers, and you wish to calculate how many even
numbers are there. Using a for loop, write a program that prints number of
even numbers in a list.

Solution:

import random

random.seed()

l = []

for i in range(0, 100): l.append(random.randint(0, 100))

evenCount = 0

for numbers in l:

               if numbers%2 == 0: evenCount+=1

print evenCount

 

2.      Print a multiplication table for number from 1 to a given number.

Solution:

for i in range(1, n+1):

               for j in range(1, 10): print i*j

The second exercise involves two for loops, one inside another (called
nested loops, and nested loops are used in many ways).

Have fun.

Cheers,

Joseph

 

 

Other related posts:

  • » [pythonvis] Some simple exercises for using loops - Joseph Lee