• No results found

Assignment: Find the factors of a number

In document Real Python Part 1 (Page 70-73)

1. Write a script “factors.py” that includes a function to find all of the integers that divide evenly into an integer provided by the user. A sample run of the program should look like this (with the user’s input highlighted in bold):

1 >>>

2 Enter a positive integer: 12

3 1 is a divisor of 12

You should use the % operator to check divisibility. This is called the “modulus operator” and is represented by a percent symbol in Python. It returns the remainder of any division. For instance, 3 goes into 16 a total of 5 times with a remainder of 1, therefore 16 % 3 returns 1. Meanwhile, since 15 is divisible by 3, 15 % 3 returns 0.

Also keep in mind that raw_input() returns a string, so you will need to convert this value to an integer before using it in any calculations.

There are two main keywords that help to control the flow of programs in Python: break and continue.

These keywords can be used in combination with for and while loops and with if statements to allow us more control over where we are in a loop.

Let’s start with break, which does just that: it allows you to break out of a loop. If we wanted to break out of a for loop at a particular point, our script might look like this:

1 for i in range(0, 4):

2 if i == 2:

3 break

4 print i

5 print "Finished with i = ", str(i)

Without the if statement that includes the break command, our code would normally just print out the following output:

1 >>>

2 Finished with i = 3

3 >>>

Instead, each time we run through the loop, we are checking whether i == 2. When this is True, we break out of the loop; this means that we quit the for loop entirely as soon as we reach the break keyword. Therefore, this code will only display:

1 >>>

2 Finished with i = 2

3 >>>

Notice that we still displayed the last line since this wasn’t part of the loop. Likewise, if we were in a loop inside another loop, break would only break out of the inner loop; the outer loop would continue to run (potentially landing us back inside the inner loop again).

Much like break, the continue keyword jumps to the end of a loop; however, instead of exiting a loop entirely, continue says to go back to the top of the loop and continue with the next item of the loop.

For instance, if we had used continue instead of break in our last example:

1 for i in range(0, 4):

2 if i == 2:

3 continue

4 print i

5 print "Finished with i = ", str(i)

We’re now skipping over the “print i” command when our if statement is True, and so our output includes everything from the loop except displaying i when i == 2:

1 >>>

2 Finished with i = 3

3 >>>

NOTES: It’s always a good idea to give short but descriptive names to your variables that make it easy to tell what they are supposed to represent. The letters i, j and k are exceptions because they are so common in programming; these letters are almost always used when we need a “throwaway” number solely for the purpose of keeping count while working through a loop.

Loops can have their own else statements in Python as well, although this structure isn’t used very frequently. Tacking an else onto the end of a loop will make sure that your else block always runs after the loop unless the loop was exited by using the break keyword. For instance, let’s use a for loop to look through every character in a string, searching for the upper-case letter X:

1 phrase = "it marks the spot"

2

3 for letter in phrase:

4 if letter == "X":

5 break

6 else:

7 print "There was no 'X' in the phrase"

Here, our program attempted to find “X” in the string phrase, and would break out of the for loop if it had. Since we never broke out of the loop, however, we reached the else statement and displayed that “X” wasn’t found. If you try running the same program on the phrase “it marks Xthe spot” or some other string that includes an “X”, however, there will be no output at all because the block of code in the else will not be run.

Likewise, an “else” placed after a while loop will always be run unless the while loop has been exited using a break statement. For instance, try out the following script:

1 tries = 0

10 print "Suspicious activity. The authorities have been alerted."

Here, we’ve given the user three chances to enter the correct password. If the password matches, we break out of the loop. Otherwise (the first else), we add one to the “tries” counter. The second “else”

block belongs to the loop (hence why it’s less indented than the first “else”), and will only be run if we don’t break out of the loop. So when the user enters a correct password, we do not run the last line of code, but if we exit the loop because the test condition was no longer True (i.e., the user tried three incorrect passwords), then it’s time to alert the authorities.

A commonly used shortcut in Python is the “+=” operator, which is shorthand for saying “increase a number by some amount”. For instance, in our last code xample above, instead of the line:tries

= tries + 1 We could have done the exact same thing (adding1 to tries) by saying: tries += 1 In fact, this works with the other basic operators as well; -= means “decrease”, *= means “multiply by”, and /= means “divide by”.

For instance, if we wanted to change the variable tries from its original value to that value multiplied by 3, we could shorten the statement to say: tries *= 3

Review exercises:

1. Use a break statement to write a script that prompts the users for input repeatedly, only ending when the user types “q” or “Q” to quit the program; a common way of creating an infinite loop is to write “while True:”

2. Combine a for loop over a range() of numbers with the continue keyword to print every number from 1 through 50 except for multiples of 3; you will need to use the % operator.

In document Real Python Part 1 (Page 70-73)