Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
The Python Workshop

You're reading from   The Python Workshop Learn to code in Python and kickstart your career in software development or data science

Arrow left icon
Product type Paperback
Published in Nov 2019
Publisher Packt
ISBN-13 9781839218859
Length 608 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (6):
Arrow left icon
Andrew Bird Andrew Bird
Author Profile Icon Andrew Bird
Andrew Bird
Graham Lee Graham Lee
Author Profile Icon Graham Lee
Graham Lee
Corey Wade Corey Wade
Author Profile Icon Corey Wade
Corey Wade
Dr. Lau Cher Han Dr. Lau Cher Han
Author Profile Icon Dr. Lau Cher Han
Dr. Lau Cher Han
Olivier Pons Olivier Pons
Author Profile Icon Olivier Pons
Olivier Pons
Mario Corchero Jiménez Mario Corchero Jiménez
Author Profile Icon Mario Corchero Jiménez
Mario Corchero Jiménez
+2 more Show less
Arrow right icon
View More author details
Toc

Table of Contents (13) Chapters Close

Preface 1. Vital Python – Math, Strings, Conditionals, and Loops 2. Python Structures FREE CHAPTER 3. Executing Python – Programs, Algorithms, and Functions 4. Extending Python, Files, Errors, and Graphs 5. Constructing Python – Classes and Methods 6. The Standard Library 7. Becoming Pythonic 8. Software Development 9. Practical Python – Advanced Topics 10. Data Analytics with pandas and NumPy 11. Machine Learning Appendix

Loops

"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:

  1. The start of the loop
  2. The end of the loop
  3. The increment between numbers in the loop

Python distinguishes between two fundamental kinds of loops: while loops, and for loops.

The while 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:

  • Initialize the variable: Loops need to be initialized with a variable. The variable is going to change throughout the loop. The naming of the variable is up to you. i is often chosen because it stands for incrementor. An example is i = 1.
  • Set up the while loop: The 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:.
  • Instructions: The instructions include all indented lines after the colon. Anything could be printed, any function could be called, and any number of lines may be executed. It all depends on the program. As long as the code is syntactically correct, generally speaking, anything goes. This part of the loop is going to run over and over as long as the aforementioned condition is true. An example is print(i).
  • Increment: The incrementor is a crucial part of this example. Without it, the preceding code will never stop running. It will print 1's endlessly because 1 is always less than 10. Here, you increment by 1, but you could also increment by 2, or any other number. An example is i += 1.

Now that you understand the separate pieces, you should look at how it works together:

  1. The variable is initialized as 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.
  2. After all indented code after the colon has run, the loop is executed again by returning to the while keyword.
  3. The 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.
  4. The 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.
  5. The while loop continues to increment and print out numbers until reaching the number 10.
  6. The 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.
  7. The 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.

An Infinite Loop

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

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.

Activity 4: Finding the Least Common Multiple (LCM)

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:

  1. Set a pair of variables as equal to 24 and 36.
  2. Initialize the while loop, based on a Boolean that is True by default, with an iterator.
  3. Set up a conditional to check whether the iterator divides both numbers.
  4. Break the while loop when the LCM is found.
  5. Increment the iterator at the end of the loop.
  6. 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.

Programs

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.

Exercise 18: Calculating 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:

  1. Open a new Jupyter Notebook.
  2. Prompt the user to enter a number to see if it's a perfect square:
    print('Enter a number to see if it\'s a perfect square.')
  3. Set a variable as equal to input(). In this case let's enter 64:
    number = input()
  4. Ensure the user input is a positive integer:
    number = abs(int(number))
  5. Choose an iterator variable:
    i = -1
  6. Initialize a Boolean to check for a perfect square:
    square = False
  7. Initialize a while loop from -1 to the square root of the number:
    while i <= number**(0.5):
  8. Increment i by 1:
      i += 1 
  9. Check the square root of the number:
      if i*i == number:   
  10. Indicate that we have a perfect square:
        square = True   
  11. break out of the loop:
        break
  12. If the number is square, print out the result:
    if square:
      print('The square root of', number, 'is', i, '.')
  13. If the number is not a square, print out this result:
    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.

Exercise 19: Real Estate 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:

  1. Open a new Jupyter Notebook.
  2. Begin by stating a market price:
    print('A one bedroom in the Bay Area is listed at $599,000')
  3. Prompt the user to make an offer on the house:
    print('Enter your first offer on the house.')
  4. Set offer as equal to input():
    offer = abs(int(input()))
  5. Prompt the user to enter their best offer for the house:
    print('Enter your best offer on the house.')
  6. Set best as equal to input():
    best = abs(int(input()))
  7. Prompt the user to choose increments:
    print('How much more do you want to offer each time?')
  8. Set increment as equal to input():
    increment = abs(int(input()))
  9. Set offer_accepted as equal to False:
    offer_accepted = False
  10. Initialize the for loop from offer to best:
    while offer <= best:
  11. If the offer is greater than 650000, they get the house:
      if offer >= 650000:
        offer_accepted = True
        print('Your offer of', offer, 'has been accepted!')
        break
  12. If the offer does not exceed 650000, they don't get the house:
      print('We\'re sorry, you\'re offer of', offer, 'has not been accepted.' )
  13. Add increment to offer:
      offer += increment

    You should get the following output:

    Figure 1.18: Output showing the conditions mentioned in the code using loops

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 Loop

The for loops are similar to while loops, but they have additional advantages, such as being able to iterate over strings and other objects.

Exercise 20: Using for Loops

In this exercise, you will utilize for loops to print the characters in a string in addition to a range of numbers:

  1. Open a new Jupyter Notebook.
  2. Print out the characters of 'Portland':
    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.

  3. You use a lower bound of 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.

  4. Now use 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.

  5. Use a step increment to count down from 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.

  6. Now, 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.

The continue Keyword

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.

Activity 5: Building Conversational Bots Using Python

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:

  1. Ask the user at least two questions.
  2. Respond to each answer. Include the answer in the response.

For the second bot, the steps are as follows:

  1. Ask a question that can be answered with a number scale, such as "On a scale of 1-10…".
  2. Respond differently depending on the answer given.
  3. State a different question following each answer that can be answered with a number scale.
  4. Respond differently depending on the answer given.

    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.

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.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime