Day: August 7, 2017

Factors of a number using python

This exercise is to find all the factors of a given number. Remember that a factor divides evenly into a number without leaving a remainder. We can use the modulo operator (%) to check for any remainder. The program will check all integers from 2 up to but not including the original number. To loop through those numbers we will use the for loop combined with the range() function.

number = int(input("Enter the number?"))
for i in range(2,number):
    remainder = number % i
    quotient = number // i
    print(number,"=",i,"x",quotient,"+ remainder",remainder)
    if remainder == 0:
        print("remainder is zero so",i,"is a factor")
    else:
        print("remainder is not zero so",i,"is not a factor")

Using print() in this way shows clearly the flow of the program. However, two lines of code for each potential factor is a lot to read through. To reduce the number of lines of code, print() lets us specify a different ending than a new line. If we specify end=’ ‘ then print() will end the line with a space rather than a new line significantly reducing the number of lines of output.

The following program ignores output when the number is not a factor, and displays all the factors on the same line, with a final message whether the original number is prime or composite. Instead of asking for the number to be entered, the program finds all factors for all numbers between 2 and 99 inclusive.

for number in range(2,100):
    print(number,'factors:', end=' ')
    prime=True
    for i in range(2,number):
        if number%i == 0:
            print(i, end=' ')
            prime=False
    if prime:
        print('prime')
    else:
        print('composite')
Categories: CoderDojo

Guessing number game in Python

This exercise is to write a program which asks the user to guess a number and the program will give hints to help the user guess the correct answer.

To display a prompt waiting for a user to enter some data, we use the input() function. The input() function provides the data as a string, which is a sequence of letters. To convert to an integer number we use the int() function.

To control the flow of the program based on the user’s answers, we use if and elif statements (elif is short for “else if”).

answer=15
guess=None
while guess != answer:
    guess=int(input("Guess a number between 0 and 50 ? "))
    if guess > answer:
        print("too high")
    elif guess < answer:
        print("too low")
print("Yes. Answer is ", answer)

Importing more functionality

Sometimes we want more functionality than is provided in the base python system. In our example we want a random number generator which is available in the random module (library). The program becomes a lot more interesting now, because we can’t see the answer by reading the source code.

import random
answer=random.randint(0,50)
guess=None
while guess != answer:
    guess=int(input("Guess a number between 0 and 50 ? "))
    if guess > answer:
        print("too high")
    elif guess < answer:
        print("too low")
print("Yes. Answer is ", answer)

In the previous countdown examples, we can put a timer to ensure the countdown happens one second at a time.

import time
x=10
while x>0:
    print(x)
    x-=1
    time.sleep(1)
print("blast off")
Categories: CoderDojo

Getting started with Python

There are many online resources for beginning in python. Here are a few

https://wiki.python.org/moin/BeginnersGuide/NonProgrammers – Python’s own suggestions for getting started
http://www.letslearnpython.com/learn/ – An online tutorial for kids used at PyCon each year
http://kata.coderdojo.com/wiki/Python_Path – Some international CoderDojo resources

At Kenmore CoderDojo Term 3 2017 we are going to be using Python 3. We will also be using Python with Minecraft. For full setup instructions, refer to https://www.triptera.com.au/wordpress/2017/06/02/coderdojo-minecraft-with-python-setup/

Python shell

At our first session, we installed Python 3.6.2 and used the IDLE development environment for running python in a shell.

Python can use operators +, -, *, /, //, % and ** to preform mathematical operations

>>> 5 + 3
8
>>> 5 - 3
2
>>> 5 * 3
15
>>> 5 / 3
1.666666666667
>>> 5 // 3
1
>>> 5 % 3
2
>>> 5 ** 3
125

+ addition
- subtraction
* multiplication
/ division (decimal)
// division (integer)
% modulo (remainder from division)
** to the power of

Variables

To store data in memory, create a name for the memory location, and assign it using the = sign. These memory locations are called variables because you can change the data in them. Type the variable name by itself to see the value stored in it. You can use variables in mathematical equations.

>>>speed=50
>>>duration=3
>>>speed
50
>>>speed * duration
150

Python program

When using the shell the commands are not saved. By putting the commands in a file they can be run over and over again without having to be retyped. In IDLE choose New File from the File menu and type the following

print(3)
print(2)
print(1)
print("blast off")

Save this file from the File menu. From the Run menu select Run module F5. Every time you run it you will see the same output in the shell window.

3
2
1
blast off

Using loops to save typing

Loops are sections of code which are run multiple times. while loops will keep looping until a specified condition is True. The indented lines indicate which part of the code is included in the loop.

x = 5
while x > 0:
    print(x)
    x -= 1
print("blast off")

The condition is x > 0 which is True for 10 loops and then becomes False when the value of x is zero.
The command x -= 1 is a shorthand for telling python to reduce the value of x by 1 every time it is run.
This program gives the following output every time it is run.

5
4
3
2
1
blast off

Only one line needs to be changed to start the countdown from a different number.

Categories: CoderDojo