Python Programming Practice-Miscellaneous Topics I

Created with Sketch.

Python Programming Practice-Miscellaneous Topics I



Very often we want our programs to count how many times something happens. For instance, a video game may need to keep track of how many turns a player has used, or a math program may want to count how many numbers have a special property. The key to counting is to use a variable to keep the count.

Example 1 This program gets 10 numbers from the user and counts how many of those numbers are greater than 10.

count = 0
fori in range (10):
num = eval ( input ( ' Enter a number: ' )) 
if num>10:
print ( ' There are ' , count, ' numbers greater than 10. ' )


Think of the count variable as if we are keeping a tally on a piece of paper. Every time we get a number larger than 10, we add 1 to our tally. In the program, this is accomplished by the line count=count+1 . The first line of the program, count=0 , is important. Without it, the Python interpreter would get to the count=count+1 line and spit out an error saying something about not knowing what count is. This is because the first time the program gets to this line, it tries to do what it says: take the old value of count , add 1 to it, and store the result in count . But the first time the program gets there, there is no old value of count to use, so the Python interpreter doesn’t know what to do. To avoid the error, we need to define count , and that is what the first


line does. We set it to 0 to indicate that at the start of the program no numbers greater than 10 have been found.

Counting is an extremely common thing. The two things involved are:

1. count=0 — Start the count at 0.

2. count=count+1 — Increase the count by 1.

Example 2 This modification of the previous example counts how many of the numbers the user enters are greater than 10 and also how many are equal to 0. To count two things we use two count variables.

count1 = 0 
count2 = 0
for i in range (10):
num = eval ( input ( ' Enter a number: ' )) 
if num>10:
if num==0:
print ( ' There are ' , count1, ' numbers greater than 10. ' )
print ( ' There are ' , count2, ' zeroes. ' )


Example 3 Next we have a slightly trickier example. This program counts how many of the

squares from 1 2 to 100 2 end in a 4.

count = 0
for i in range (1,101):
if (i**2)%10==4:
count = count + 1print (count)


A few notes here: First, because of the aforementioned quirk of the range function, we need to use range (1,101) to loop through the numbers 1 through 100. The looping variable i takes on those

values, so the squares from 1 2 to 100 2 are represented by i**2 . Next, to check if a number ends

in 4, a nice mathematical trick is to check if it leaves a remainder of 4 when divided by 10. The modulo operator, % , is used to get the remainder.



Closely related to counting is summing, where we want to add up a bunch of numbers.

Leave a Reply

Your email address will not be published. Required fields are marked *