-
Book Overview & Buying
-
Table Of Contents
The Python Workshop
By :
"Write the first 100 numbers."
There are several assumptions implicit in this seemingly simple command. The first is that the student knows where to start, namely at number 1. The second assumption is that the student knows where to end, at number 100. And the third is that the student understands that they should count by 1.
In programming, this set of instructions may be executed with a loop.
There are three key components to most loops:
Python distinguishes between two fundamental kinds of loops: while loops, and for loops.
In a while loop, a designated segment of code repeats provided that a particular condition is true. When the condition evaluates to false, the while loop stops running. The while loops print out the first 10 numbers.
You could print the first 10 numbers by implementing the print function 10 times, but using a while loop is more efficient, and it scales easily. In general, it's not a good idea to copy and paste while coding. If you find yourself copying and pasting, there's probably a more efficient way. Let's have a look at the following example code block:
i = 1 while i <= 10: print(i) i += 1
You should get the following output:
1 2 3 4 5 6 7 8 9 10
You can break down the preceding code block and find out what's happening in concrete steps:
i is often chosen because it stands for incrementor. An example is i = 1.while loop starts with the while keyword. Following while is the chosen variable. After the variable comes the condition that must be met for the loop to run. In general, the condition should have some way of being broken. When counting, the condition usually includes an upper limit, but it could also be broken in other ways, such as i != 10. This line of code is the most critical piece of the loop. It sets up how many times the loop is expected to run. An example is while i <= 10:.print(i).i += 1.Now that you understand the separate pieces, you should look at how it works together:
1. The while loop checks the condition. 1 is less than or equal to 10. 1 is printed. 1 is added to i. We increment to i = 2.while keyword.while loop checks the condition again. 2 is less than or equal to 10. 2 is printed to the console. 1 is added to i. We now increment to i = 3.while loop checks the condition again. 3 is less than or equal to 10. 3 is printed to the console. 1 is added to i. We increment to i = 4.while loop checks the condition. 10 is less than or equal to 10. 10 is printed to the console. 1 is added to i. Now, increment to i = 11.while loop checks the condition. 11 is not less than or equal to 10. We break out of the loop by moving beyond the indentation.Note
You will get stuck in infinite loops. It happens to everyone. At some point, you will forget to add the increment, and you will be stuck in an infinite loop. In Jupyter Notebooks, just restart the kernel.
Now you should have a look at infinite loops. The following code snippet supports this topic:
x = 5 while x <= 20: print(x)
Python often runs very quickly. If something is taking much longer than expected, an infinite loop might be the culprit, as in the aforementioned code snippet. A developer here would be setting all the variables and conditions right to avoid the infinite loop case. An example of a well-written Python code is as follows:
x = 5 while x<= 20: print(x) x += 5
break is a special keyword in Python that is specifically designed for loops. If placed inside of a loop, commonly in a conditional, break will immediately terminate the loop. It doesn't matter what comes before or after the loop. The break is placed on its own line, and it breaks out of the loop.
To practice, you should print the first number greater than 100 that is divisible by 17.
The idea is that you are going to start at 101 and keep counting until you find a number divisible by 17. Assume you don't know what number to stop at. This is where break comes into play. break will terminate the loop. You can set our upper bound at some number that you know you will never reach and break out of the loop when you get there:
# Find first number greater than 100 and divisible by 17.
x = 100
while x <= 1000:
x += 1
if x % 17 == 0:
print('', x, 'is the first number greater than 100 that is divisible by 17.')
break
The x += 1 iterator is placed at the beginning of the loop. This allows us to start with 101. The iterator may be placed anywhere in the loop.
Since 101 is not divisible by 17, the loop repeats, and x = 102. Since 102 is divisible by 17, the print statement executes and we break out of the loop.
This is the first time you have used double indentation. Since the if conditional is inside of a while loop, it must be indented as well.
In this activity, you will find the LCM of two divisors. The LCM of two divisors is the first number that both divisors can divide.
For instance, the LCM of 4 and 6 is 12, because 12 is the first number that both 4 and 6 can divide. You will find the LCM of 2 numbers. You will set the variables, then initialize a while loop with an iterator and a Boolean that is True by default. You will set up a conditional that will break if the iterator divides both numbers. You will increase the iterator and print the results after the loop completes.
In this activity, using the following steps, you need to find the LCM of 24 and 36.
The steps are as follows:
24 and 36.while loop, based on a Boolean that is True by default, with an iterator.Print the results.You should get the following output:
The Least Common Multiple of 24 and 36 is 72.
Note
The solution for this activity can be found via this link.
You have been writing programs all through this book. Every chunk of executable code that can be saved and run on demand is a computer program. You have written programs that greeted users, and you just wrote a program to compute the LCM of a given number in Activity 4, Finding the Least Common Multiple (LCM).
Now that you have a lot of tools under our belt, you can combine them to write some pretty interesting programs. You know how to generate input from a user, we know how to convert the input into desired types, and you know how to use conditionals and loops to iterate through cases and print various results depending upon the outcome.
Later in the book, you will get into the details of saving and testing programs. For now, you should work on some interesting examples and exercises. For instance, in the next exercise, you will build a program step by step to identify perfect squares.
The goal of this exercise is to prompt the user to enter a given number and find out whether it is a perfect square.
The following steps in this exercise will help you with this:
print('Enter a number to see if it\'s a perfect square.')input(). In this case let's enter 64:number = input()
number = abs(int(number))
i = -1
square = False
while loop from -1 to the square root of the number:while i <= number**(0.5):
i by 1:i += 1
number:if i*i == number:
square:square = True
break out of the loop:break
square, print out the result:if square:
print('The square root of', number, 'is', i, '.')else:
print('', number, 'is not a perfect square.')You should get the following output:
The square root of 64 is 8.
In this exercise, you have written a program to check to see whether the user's number is a perfect square.
In the next exercise, you are going to build a similar program that will accept inputs from the user. You need to provide the best possible offer for a real estate and either accept or decline the offer.
The goal of this exercise is to prompt the user to bid on a house and let them know if and when the bid has been accepted.
The following steps in this exercise will help you with this:
print('A one bedroom in the Bay Area is listed at $599,000')print('Enter your first offer on the house.')offer as equal to input():offer = abs(int(input()))
print('Enter your best offer on the house.')best as equal to input():best = abs(int(input()))
print('How much more do you want to offer each time?')increment as equal to input():increment = abs(int(input()))
offer_accepted as equal to False:offer_accepted = False
for loop from offer to best:while offer <= best:
offer is greater than 650000, they get the house: if offer >= 650000:
offer_accepted = True
print('Your offer of', offer, 'has been accepted!')
breakoffer does not exceed 650000, they don't get the house: print('We\'re sorry, you\'re offer of', offer, 'has not been accepted.' )increment to offer:offer += increment
You should get the following output:

Figure 1.18: Output showing the conditions mentioned in the code using loops
In this exercise, you have prompted the user to bid for a house and let them know when and if the bid was accepted.
The for loops are similar to while loops, but they have additional advantages, such as being able to iterate over strings and other objects.
In this exercise, you will utilize for loops to print the characters in a string in addition to a range of numbers:
for i in 'Portland': print(i)
You should get the following output:
P o r t l a n d
The for keyword often goes with the in keyword. The i variable is generic. The phrase, for i in, means that Python is going to check what comes next and look at its individual components. Strings are composed of characters, so Python will do something with each of the individual characters. In this particular case, Python will print out the individual characters, as per the print(i) command.
What if we want to do something with a range of numbers? Can for loops be used for that? Absolutely. Python provides another keyword, range, to access a range of numbers. range is often defined by two numbers, the first number, and the last number, and it includes all numbers in between. Interestingly, the output of range includes the first number, but not the last number. You will see why in a minute.
1 and an upper bound of 10 with range to print 1-9:for i in range(1,10): print(i)
You should get the following output:
1 2 3 4 5 6 7 8 9
The range does not print the number 10.
range with one bound only, the number 10, to print the first ten numbers:for i in range(10): print(i)
You should get the following output:
0 1 2 3 4 5 6 7 8 9
So, range(10) will print out the first 10 numbers, starting at 0, and ending with 9.
Now let's say that you want to count by increments of 2. You can add a third bound, a step increment, to count up or down by any number desired.
Use a step increment to count the even numbers through 10:
for i in range(1, 11, 2): print(i)
You should get the following output:
1 3 5 7 9
Similarly, you can count down using negative numbers, which is shown in the next step.
3 to -1:for i in range(3, 0, -1): print(i)
You should get the following output:
3 2 1
And, of course, you can use nested loops, which is shown in the next step.
print each letter of your name three times:name = 'Corey' for i in range(3): for i in name: print(i)
You should get the following output:
C o r e y C o r e y C o r e y
In this exercise, you have utilized loops to print any given number of integers and characters in a string.
continue is another Python keyword designed for loops. When Python reaches the continue keyword, it stops the code and goes back to the beginning of the loop. continue is similar to break because they both interrupt the loop process, but break terminates the loop, continue continues the loop from the beginning.
Let's look at an example of continue in practice. The following code prints out every two-digit prime number:
for num in range(10,100): if num % 2 == 0: continue if num % 3 == 0: continue if num % 5 == 0: continue if num % 7 == 0: continue print(num)
You should get the following output:
11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Let's go through the beginning of the code. The first number to check is 10. The first line checks to see if 10 can be divided by 2. Since 2 does divide 10, we go inside the conditional and reach the continue keyword. Executing continue returns to the start of the loop.
The next number that is checked is 11. Since 2,3,5, and 7 do not divide 11, you reach the final line and print the number 11.
You are working as a Python developer and you are building two conversational bots for your clients. You create a list of steps beforehand to help you out, as outlined in the following section. These steps will help you build two bots that take input from the user and produce a coded response.
The aim of this activity is to use nested conditionals to build two conversational bots. In this activity, you will build two conversational bots. The first bot will ask the user two questions and include the user's answer in each of its follow-up responses. The second bot will ask a question that requires a numerical answer. Different responses will be given to a different number of scales. The process will be repeated for a second question.
The steps are as follows:
For the first bot, the steps are as follows:
For the second bot, the steps are as follows:
On a scale of 1-10…". Note
The second bot should be written with nested conditionals.
Hint - casting may be important.
The expected output for bot 1 is as follows:
We're kindred spirits, Corey.Talk later.
The expected output for bot 2 is as follows:
Figure 1.19: Expected outcome from one of the possible values entered by the user.
Note
The solution for this activity can be found via this link.
Change the font size
Change margin width
Change background colour