{python}

Introduction to Python - Lecture 3

Zohair ul Hasan

Recap

  • Yesterday we played with the Python Shell
  • Learned what expressions, values, operators, datatypes, and variables are
  • Learned string concatenation and replication
  • Learned the difference between statements and expressions - and saw assignment statements in action

Recap

Recap

Yesterday's assignment?

Today's Lecture

In this lecture, we will talk about:

 

  • A new data type (boolean)
  • New operators (comparison operators and boolean operators)
  • Conditions (and how they differ from expressions)
  • Code blocks in Python
  • New statements (control statements i.e. if statement, while loop statment, for loop statement)
  • The range() function
  • Importing modules

Introduction

So far, we've seen programs running as a series of instructions

The strength of programming, however, lies in the ability to skip, repeat, or choose one of several instructions based on certain conditions

Introduction

We can choose which pieces of code to run using flow control statements

We will explore them in detail in this lecture

Introduction

Introduction

But before we learn flow control statements in Python, we need to learn how to represent the "yes" and "no" options we saw in the flow chart

We represent the yes and no values using a new data type called the "boolean" data type

Boolean Datatype

While the integer, floating point and string data types have an unlimited number of possible values, the Boolean data type only has two values: True and False

Boolean Datatype

Boolean values:

  • Do not need to be surrounded with quotes like Strings do

 

  • Always start with a capital T or F, with the rest of the word being in lowercase

Boolean Datatype

>>> True
True
>>> False
False
>>> spam = True
>>> spam
True
>>> type(spam)
<class 'bool'>
>>> true
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'true' is not defined. Did you mean: 'True'?
>>> True = 2 + 2
  File "<stdin>", line 1
    True = 2 + 2
    ^^^^
SyntaxError: cannot assign to True

Comparison Operators

Comparison Operators compare two values and evaluate down to a single Boolean value

Operator Meaning
== Equal to
!= Not equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to

Comparison Operators

These operators evaluate to a True or False value depending on the given values

Comparison Operators

>>> 42 == 42
True
>>> 42 == 99
False
>>> 2 != 3
True
>>> 2 != 2
False
>>> 'hello' == 'hello'
True
>>> 'hello' == 'Hello'
False
>>> 'dog' != 'cat'
True
>>> True == True
True
>>> True != False
True
>>> 42 == 42.0
True
>>> 42 == '42'
False

Comparison Operators

>>> 42 < 100
True
>>> 42 > 100
False
>>> 42 < 42
False
>>> egg_count = 42
>>> egg_count <= 42
True
>>> my_age = 29
>>> my_age >= 10
True

== versus =

  • The == operator (equal to) asks whether two values are the same as each other (it is an expression that evaluates to a True or False value)

 

  • The = operator (assignment) puts the value on the right into the variable on the left

Boolean Operators

Just like the comparison operators, boolean operators are used to compare boolean values

There are three boolean operators in Python:

  • and
  • or
  • not

The and operator

The and operator evaluates an expression to True if the expression on the left handside as well as the expression on the right hand side evaluates to True

Otherwise it evaluates to false

The and operator

>>> True and True
True
>>> True and False
False
>>> False and True
False
>>> False and False
False

Truth table for the and operator

Expression Evaluates to...
True and True True
True and False False
False and True False
False and False False

Truth table for the or operator

Expression Evaluates to...
True or True True
True or False True
False or True True
False or False False

The not operator

Unlike the and and or operators, the not operator operates on a single Boolean value (or expression)

The not operator simply evaluates to the opposite boolean value

The not operator

>>> not True
False
>>> not False
True

Truth table for the not operator

Expression Evaluates to...
True False
False True

Mixing boolean and comparison operators

Boolean operators are named so because they operator only on boolean expressions

Since comparison operators (==, <, >, <=, >=) always evaluate down to boolean values, we can combine them together 

Mixing boolean and comparison operators

>>> (4 < 5) and (5 < 6)
True
>>> (4 < 5) and (9 < 6)
False
>>> (1 == 2) or (2 == 2)
True

Mixing boolean and comparison operators

Mixing boolean and comparison operators

>>> 2 + 2 == 4 and not 2 + 2 == 5 and 2 * 2 == 2 + 2
True

Flow control statements

Flow controls statements start with a condition, followed by a block of code called the clause

Conditions

Conditions are expressions that evaluate to a Boolean value (i.e. True/False)

Block of code

Lines of Python code can be grouped into "blocks"

There are three rules for blocks:

1. Blocks begin when the indentation  increases

2. Blocks can contain other blocks

3. Blocks end when the indentation reduces to the containing block's indentation level

Block of code

  name = 'Mary'
  password = 'swordfish'
  if name == 'Mary':
    print('Hello, Mary')
    if password == 'swordfish':
        print('Access granted.')
    else:
        print('Wrong password.')

Block 1

Block 2

Block 3

Flow Control Statements: the if statement

An if statement's clause (the block following the if statement) will execute if the if statement's condition is True

The clause is skipped if the condition is False

Flow Control Statements: the if statement

In plain English, an if statement could be read as, “If this condition is true, execute the code in the clause.”

Flow Control Statements: the if statement

In Python, an if statement consists of the following:

  • The if keyword
  • A condition (i.e. an expression that evaluates to True or False)
  • A colon
  • Starting on the next line, an indented block of code (called the if clause)

Flow Control Statements: the if statement

name = 'Alice'
if name == 'Alice':
    print('Hi, Alice.')

Flow Control Statements: the else statement

An else statement's clause (the block following the if statement) will execute if the if statement's condition is False

The clause is skipped if the condition is True

Flow Control Statements: the else statement

In plain English, an else statement could be read as, “If this condition is true, execute this code. Otherwise, execute that code”

Flow Control Statements: the else statement

In Python, an else statement consists of the following:

  • The else keyword
  • A colon
  • Starting on the next line, an indented block of code (called the else clause)

Flow Control Statements: the else statement

name = 'Zohair'
if name == 'Alice':
    print('Hi, Alice.')
else:
    print('Hello, stranger.')

Flow Control Statements: the else statement

Flow Control Statements: the elif statement

The elif statement is an “else if” statement that always follows an if or another elif statement.

It provides another condition that is checked only if all of the previous conditions were False.

Flow Control Statements: the elif statement

In Python, an elif statement consists of the following:

  • The elif keyword
  • A condition (an expression that evaluates to True or False)
  • A colon
  • Starting on the next line, an indented block of code (called the elif clause)

Flow Control Statements: the elif statement

name = 'Zohair'
age = 9
if name == 'Alice':
    print('Hi, Alice.')
elif age < 13:
    print('You are not Alice, kid.')

Flow Control Statements: the elif statement

Flow Control Statements: the elif statement

The elif clause executes if age < 12 is True and name == 'Alice' is False. However, if both of the conditions are False, then both of the clauses are skipped

Flow Control Statements

Now let's do an activity to practice control statements: https://itp.zohair.dev/activities/control-statements

Loop statements

Now let's do an activity to learn about loops: https://itp.zohair.dev/activities/loops

Importing Modules

Now let's do an activity to learn about importing modules: https://itp.zohair.dev/activities/importing-modules

Your turn

Using the things we learned in this lecture, you will now be tasked to write a program

Your turn

You will implement a "guess the number" game

The game will save a random secret number at the start of the program between 1 and 20

It will then prompt the user for their guess. If their guess is correct, it will let them know. If it is too high or too low, it will let them know too.

Your turn

Here is sample output for the game:

I am thinking of a number between 1 and 20.
Take a guess.
10
Your guess is too low.
Take a guess.
15
Your guess is too low.
Take a guess.
17
Your guess is too high.
Take a guess.
16
Good job! You guessed my number in 4 guesses!

User input

Flowchart at the start

Flowchart now

Quiz!