Counting in Python
In some problems we need to count. Consider this problem.
The positive three-digit integer N has a ones digit of 0. What is the probability that N is divisible by 4? Express your answer as a common fraction.
To solve this problem we could try the first three digit number (i.e. 100) and find that it is divisble by 4. Then we could try 110, 120, 130, and so on. Or, we could write some Python code to do this for us.
To do this without too much work we will want to use a loop. A loop repeats some Python code for us so we don't have to keep writing the same thing over and over again. In this case we want to check to see if numbers are divisible by 4 over and over again and we want to count how many are divisible by 4.
We need to know three things to complete this problem. First, we want to build a list of all 3-digit numbers whose ones digit is 0. This can be done with the range function in Python. If we write range(100,1000,10) we get a list of [100, 110, 120, 130, ... , 990]. You can try range(100,1000,10) in the Python Shell to see this really works. Lists are powerful structures in Python. We can use lists for all sorts of information.
Next, we need to see if a number is divisible by 4. We can use an if statement to do this.
if N % 4 == 0:
count = count + 1
This statement says to add one to count if N is divisible by 4. A number is divisble by 4 if the remainder after dividing by 4 is zero. N%4==0 asks if dividing N by 4 results in a 0 remainder.
Finally, we can write a for loop to use the list to check all the the possible values of N and see if they are divisible by 4.
We start out with count equal to zero. This starts us counting so that every time we find another three digit number with a zero ones digit that is divisible by 4 we can add one more to count. After the loop is done, we can print the total we found for count. Notice that indentation makes a difference. The code indented under the for loop is the code that is "in" the for loop. The print statements are "after" the for loop.
You Try It
Try this to see that it works!