Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
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

Booleans and Conditionals

Booleans, named after George Boole, take the values of True or False. Although the idea behind Booleans is rather simple, they make programming immensely more powerful.

When writing programs, for instance, it's useful to consider multiple cases. If you prompt the user for information, you may want to respond differently depending upon the user's answer.

For instance, if the user gives a rating of 0 or 1, you may give a different response than a rating of 9 or 10. The keyword here is if.

Programming based upon multiple cases is referred to as branching. Each branch is represented by a different conditional. Conditionals often start with an 'if' clause, followed by 'else' clauses. The choice of a branch is determined by Booleans, depending on whether the given conditions are True or False.

Booleans

In Python, a Boolean class object is represented by the bool keyword and has a value of True or False.

Note

Boolean values must be capitalized in Python.

Exercise 13: Boolean Variables

In this short exercise, you will use, assign, and check the type of Boolean variables:

  1. Open a new Jupyter Notebook.
  2. Now, use a Boolean to classify someone as being over 18 using the following code snippet:
    over_18 = True
    type(over_18)

    You should get the following output:

    bool

    The output is satisfied, and the type is mentioned as a Boolean, that is, bool.

  3. Use a Boolean to classify someone as not being over 21:
    over_21 = False
    type(over_21)

    You should get the following output:

    bool

In this short, quick exercise, you have learned about the bool type, one of Python's most important types.

Logical Operators

Booleans may be combined with the and, or, and not logical operators.

For instance, consider the following propositions:

A = True

B = True

Y = False

Z = False

Not simply negates the value, as follows:

not A = False

not Z = True.

And is only true if both propositions are true. Otherwise, it is false:

A and B = True

A and Y = False

Y and Z = False

Or is true if either proposition is true. Otherwise, it is false:

A or B = True

A or Y = True

Y or Z = False

Now let's use them in the following practice example.

Determine whether the following conditions are True or False given that over_18 = True and over_21 = False:

  • over_18 and over_21
  • over_18 or over_21
  • not over_18
  • not over_21 or (over_21 or over_18)
  1. You have to put this into code and first assign True and False to over_18 and over_21:
    over_18, over_21 = True, False
  2. Next you can assume the individual is over_18 and over_21:
    over_18 and over_21

    You should get the following output:

    False
  3. You now assume the individual is over_18 or over_21:
    over_18 or over_21

    You should get the following output:

    True
  4. You now assume the individual is not over_18:
    not over_18

    You should get the following output:

    False
  5. You assume the individual is not over_21 or (over_21 or over_18):
    not over_21 or (over_21 or over_18)

    You should get the following output:

    True

In the next section, we will learn about the comparison operators that go along with Booleans.

Comparison Operators

Python objects may be compared using a variety of symbols that evaluate to Booleans.

Figure 1.17 shows the comparison table with their corresponding operators:

Figure 1.17: Comparison table with its corresponding symbols

Figure 1.17: Comparison table with its corresponding symbols

Note

The = and == symbols are often confused. The = symbol is an assignment symbol. So, x = 3 assigns the integer 3 to the x variable. The == symbol makes a comparison. Thus x == 3 checks to see whether x is equivalent to 3. The result of x == 3 will be True or False.

Exercise 14: Comparison Operators

In this exercise, you will practice using comparison operators. You will start with some basic mathematical examples:

  1. Open a new Jupyter Notebook.
  2. Now, set age as equal to 20 and include a comparison operator to check whether age is less than 13:
    age = 20
    age < 13

    You should get the following output:

    False
  3. Using the following code snippet, you can check whether age is greater than or equal to 20 and less than or equal to 21:
    age >= 20 and age <= 21

    You should get the following output:

    True
  4. Now check whether age is equivalent to 21:
    age != 21

    You should get the following output:

    True
  5. Now, check whether age is equivalent to 19:
    age == 19

    You should get the following output:

    False

    The double equals sign, or the equivalent operator, ==, is very important in Python. It allows us to determine whether two objects are equal. You can now address the question of whether 6 and 6.0 are the same in Python.

  6. Is 6 equivalent to 6.0 in Python? Let's find out:
    6 == 6.0

    You should get the following output:

    True

    This may come as a bit of a surprise. 6 and 6.0 are different types, but they are equivalent. Why would that be?

    Since 6 and 6.0 are equivalent mathematically, it makes sense that they would be equivalent in Python, even though the types are different. Consider whether 6 should be equivalent to 42/7. The mathematical answer is yes. Python often conforms to mathematical truths, even with integer division. You can conclude that it's possible for different types to have equivalent objects.

  7. Now find out whether 6 is equivalent to the '6' string:
    6 == '6'

    You should get the following output:

    False

    Here, you emphasize that different types usually do not have equivalent objects. In general, it's a good idea to cast objects as the same type before testing for equivalence.

    Next, let's find out whether someone is in their 20's or 30's:

    (age >= 20 and age < 30) or (age >= 30 and age < 40)

    You should get the following output:

    True

    Parentheses are not necessary when there is only one possible interpretation. When using more than two conditions, parentheses are generally a good idea. Note that parentheses are always permitted. The following is another approach:

    (20 <= age < 30) or (30 <= age < 40)

    You should get the following output:

    True

    Although the parentheses in the preceding code line are not strictly required, they make the code more readable. A good rule of thumb is to use parentheses for clarity.

By completing this exercise, you have practiced using different comparison operators.

Comparing Strings

Does 'a' < 'c' make sense? What about 'New York' > 'San Francisco'?

Python uses the convention of alphabetical order to make sense of these comparisons. Think of a dictionary: when comparing two words, the word that comes later in the dictionary is considered greater than the word that comes before.

Exercise 15: Comparing Strings

In this exercise, you will be comparing strings using Python:

  1. Open a new Jupyter Notebook.
  2. Let's compare single letters:
    'a' < 'c'

    You should get the following output:

    True
  3. Now, let's compare 'New York' and 'San Francisco':
    'New York' > 'San Francisco'

    You should get the following output:

    False

This is False because 'New York' < 'San Francisco'. 'New York' does not come later in the dictionary than 'San Francisco'.

In this exercise, you have learned how to compare strings using comparison operators.

Conditionals

Conditionals are used when we want to express code based upon a set of circumstances or values. Conditionals evaluate Boolean values or Boolean expressions, and they are usually preceded by 'if'.

Let's say we are writing a voting program, and we want to print something only if the user is under 18.

The if Syntax

if age < 18:
    print('You aren\'t old enough to vote.')

There are several key components to a condition. Let's break them down.

The first is the 'if' keyword. Most conditionals start with an if clause. Everything between 'if' and the colon is the condition that we are checking.

The next important piece is the colon :. The colon indicates that the if clause has completed. At this point, the compiler decides whether the preceding condition is True or False.

Syntactically, everything that follows the colon is indented.

Python uses indentation instead of brackets. Indentation can be advantageous when dealing with nested conditionals because it avoids cumbersome notation. Python indentation is expected to be four spaces and may usually be achieved by pressing Tab on your keyboard.

Indented lines will only run if the condition evaluates to True. If the condition evaluates to False, the indented lines will be skipped over entirely.

Indentation

Indentation is one of Python's singular features. Indentation is used everywhere in Python. Indentation can be liberating. One advantage is the number of keystrokes. It takes one keystroke to tab, and two keystrokes to insert brackets. Another advantage is readability. It's clearer and easier to read code when it all shares the same indentation, meaning the block of code belongs to the same branch.

One potential drawback is that dozens of tabs may draw text offscreen, but this is rare in practice, and can usually be avoided with elegant code. Other concerns, such as indenting or unindenting multiple lines, may be handled via shortcuts. Select all of the text and press Tab to indent. Select all of the text and press Shift + Tab to unindent.

Note

Indentation is unique to Python. This may result in strong opinions on both sides. In practice, indentation has been shown to be very effective, and developers used to other languages will appreciate its advantages in time.

Exercise 16: Using the if Syntax

In this exercise, you will be using conditionals using the if clause:

  1. Open a new Jupyter Notebook.
  2. Now, run multiple lines of code where you set the age variable to 20 and add an if clause, as mentioned in the following code snippet:
    age = 20
    if age >= 18 and age < 21:
       print('At least you can vote.')
       print('Poker will have to wait.')

    You should get the following output:

    At least you can vote.
    Poker will have to wait.

    There is no limit to the number of indented statements. Each statement will run in order, provided that the preceding condition is True.

  3. Now, use nested conditionals:
    if age >= 18:
      print('You can vote.')
      if age >= 21:
        print('You can play poker.')

    You should get the following output:

    You can vote.

    In this case, it's true that age >= 18, so the first statement prints You can vote. The second condition, age >= 21, however, is false, so the second statement does not get printed.

In this exercise, you have learned how to use conditionals using the if clause. Conditionals will always start with if.

if else

if conditionals are commonly joined with else clauses. The idea is as follows. Say you want to print something to all users unless the user is under 18. You can address this with an if-else conditional. If the user is less than 18, you print one statement. Otherwise, you print another. The otherwise clause is preceded with else.

Exercise 17: Using the if-else Syntax

In this exercise, you will learn how to use conditionals that have two options, one following if, and one following else:

  1. Open a new Jupyter Notebook.
  2. Introduce a voting program only to users over 18 by using the following code snippet:
    age = 20
    if age < 18:
      print('You aren\'t old enough to vote.')
    else:
      print('Welcome to our voting program.')

    You should get the following output:

    Welcome to our voting program.

    Note

    Everything after else is indented, just like everything after the if loop.

  3. Now run the following code snippet, which is an alternative to the code mentioned in step 2 of this exercise:
    if age >= 18:
      print('Welcome to our voting program.')
    else:
      print('You aren\'t old enough to vote.')

    You should get the following output:

    Welcome to our voting program.

In this exercise, you have learned how to use if-else in conjunction with loops.

There are many ways to write a program in Python. One is not necessarily better than another. It may be advantageous to write faster programs or more readable programs.

A program is a set of instructions run by a computer to complete a certain task. Programs may be one line of code, or tens of thousands. You will learn important skills and techniques for writing Python programs in various chapters throughout this book.

The elif Statement

elif is short for else if. elif does not have meaning in isolation. elif appears in between an if and else clause. An example should make things clearer. Have a look at the following code snippet and copy it into your Jupyter notebook. The explanation for this code is mentioned right after the output:

if age <= 10:
  print('Listen, learn, and have fun.')
elif age<= 19:
  print('Go fearlessly forward.')
elif age <= 29:
  print('Seize the day.')
elif age <= 39:
  print('Go for what you want.')
elif age <= 59:
  print('Stay physically fit and healthy.')
else:
  print('Each day is magical.')

You should get the following output:

Seize the day.

Now, let's break down the code for a better explanation:

  1. The first line checks if age is less than or equal to 10. Since this condition is false, the next branch is checked.
  2. The next branch is elif age <= 19. This line checks if age is less than or equal to 19. This is also not true, so we move to the next branch.
  3. The next branch is elif age <= 29. This is true since age = 20. The indented statement that follows will be printed.
  4. Once any branch has been executed, the entire sequence is aborted, none of the subsequent elif or else branches are checked.
  5. If none of the if or elif branches were true, the final else branch will automatically be executed.

In the next topic, you will be learning about loops.

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
Banner background image