Overview

  • Hour 1
    • Boolean Expressions
    • Logical Operators
    • Repetition Structures
  • Hour 2
    • Repetition Structures continued
  • Hour 3
    • Programming Exercise

Lab Exercise 1

  • The intention is to complete the lab during class
  • We made an exception for last week, since it was the first one.
  • Solution is now available on a another branch of the repository

Assignment 1

  • Take note of the announcement regarding FAQs on Blackboard
  • Test cases are now available in my repo
    • Perform a fetch to add them to your fork

Lecture Notes

  • Now available on github https://github.com/benevolentprof/inf1340-2015-notebooks

Review

Booleans

  • Named after the mathematician George Boole.
  • Booleans can be True or False. (The capitalization is important.)

Boolean Expressions and Relational Operators


In [ ]:
x = 1
y = 2
y != x

Logical Operators

  • Allow you to connect multiple Boolean expressions into a compound expression
  • There are three that you need to know: and, or, and not

and

  • Both sub-expressions must be true for compound expression to be true


In [ ]:
if temperature < 20 and minutes > 12:
    print("The temperature is in the danger zone.")

or

  • One or both subexpressions must be true for the compound expression to be true


In [ ]:
if temperature < 20 or temperature > 100:
    print("The temperature is too extreme.")

Short Circuit Evaluation

  • Idea: Evaluate as little of the expression as necessary to determine truth value

and

If the expression on the left hand side of the operator is false, stop evaluating.

or

If the expression on the left hand side of the operator is true, stop evaluating.

not

  • A unary operator, meaning that it takes only one expression
  • Reverses the truth value of expression


In [ ]:
if not(temperature > 100):
    print("This is below the maximum temperature.")

Let's try

x > y and a < b

x == y or a == b

not(x > y)


In [1]:
x = 5
y = 6
a = 1000
b =  2000

x > y and a < b


Out[1]:
False

Checking Numerical Ranges

  • To check if a value is inside a range, best to use and
    • x >=20 and x <= 40
  • To check if a value is outside a range, best to use or

    • x < 20 or x > 40
  • Beware of boundaries

    • Example: You must be 18 to vote.

In [ ]:
# Not correct
if age > 18 :
    print("You can vote")

# Correct
if age >= 18 :
    print("You can vote")

# Correct, but less desirable
# Possibly incorrect if age is a float
if age > 17 :
    print("You can vote")

Repetition Structures

  • Cause a statement or a set of statements to execute repeatedly
  • There are two kinds of repetition structures
    • while, a Condition-Controlled Loop
    • for, a Count-Controlled Loop
  • Recall the vowel_or_consonant() function from last class
  • In order to repeat, need to call function again and again

In [3]:
def vowel_or_consonant():
    """
    Exercise: Vowel or Consonant
    Reads a letter of the alphabet from the user. (You can assume that it's
    lowercase.) If the user enters a, e, i, o or u then your program should
    display "vowel". If the user enters y then your program should display
    "sometimes a vowel, sometimes a consonant". Otherwise your program should
    display a message indicating that the letter is a "consonant".
    """

    vowels = list("aeiou")

    letter = raw_input("Input a letter of the alphabet: ")

    if letter in vowels:
        print("vowel")
    elif letter == "y":
        print("sometimes a vowel, sometimes a consonant")
    else:
        print("consonant")

In [5]:
vowel_or_consonant()
vowel_or_consonant()
vowel_or_consonant()


Input a letter of the alphabet: a
vowel
Input a letter of the alphabet: b
consonant

while Loop

  • Controlled loop by a conditional statement
  • Runs a statement or set of statements repeats as long as a (while) condition is true.
    • A pre-test loop
  • Two important parts: test and statements

while condition: statement statement


In [7]:
# Write a program that will echo back what the user types in

# Inputs: string from user, choice on whether to continue
# Processing: None
# Output: print string from user

# Create a variable to control the loop

keep_going = "y"

while keep_going == "y":
    user_input = raw_input("What did you say? ")
    print(user_input)
    
    keep_going = raw_input("Again? Enter y ")


What did you say? fee
fee
Again? Enter yy
What did you say? fi
fi
Again? Enter yy
What did you say? fum
fum
Again? Enter yn

In [9]:
# Write a program that will echo back what the user types in

# Inputs: string from user, choice on whether to continue
# Processing: None
# Output: print string from user

# Create a variable to control the loop

keep_going = "y"

while keep_going == "y":
    
    keep_going = raw_input("Again? Enter y ")


Again? Enter y y
Again? Enter y afsdfsdfd

Infinite Loops

  • Continue indefinitely
  • Generally undesirable
  • Can be avoided with while loops by making sure that test evaluates to false at some point

In [ ]:
# Don't do this
# This is an infinite loop, because loop condition never changes
while True:
    print("One Infinite Loop")

for Loop

  • Loop controlled by a count or list
  • Runs for a specified number of times
  • Three important parts: loop index (or target variable), loop range, and statements

for variable in [value1, value2, ...]: statement statement


In [10]:
for number in [1, 2, 3, 4, 5]:
    print(number)


1
2
3
4
5

In [11]:
for animal in ["giraffe", "otter", "bears", "panda", "capybara", "elephant", "python"]:
    print(animal)


giraffe
otter
bears
panda
capybara
elephant
python

In [12]:
for element in [5, "string", 75.62]:
    print(element)


5
string
75.62

Using the range function

  • range() creates an iterable
  • Simpler than writing out all the values

In [13]:
# These two loops are not the same!

for number in [1, 2, 3, 4, 5]:
    print(number)

for number in range(5):
    print(number)


1
2
3
4
5
0
1
2
3
4

Other uses of range


In [15]:
for number in range(1, 6):
    print(number)


1
2
3
4
5

In [18]:
for number in range(1, 50, 7):
    print(number)


1
8
15
22
29
36
43

Can use a variable to control the number of times a for loop iterates


In [ ]:
iterations = raw_input("How many times? ")
iterations = int(iterations)

for count in range(iterations):
    print(count)

Calculate a Running Total

  • A running total is a sum of numbers that accumulates with each iteration
  • The variable used to keep the running total is called an accumulator.

In [31]:
# This program calculates the sum of a series of 
# numbers entered by the user

iterations = raw_input("How many times? ")
iterations = int(iterations)

sum = 0
product = 1

for count in range(1, iterations + 1):
    sum += count
    product *= count

print(sum)
print(product)


How many times? 5
15
120

Augmented Assignment Operators

  • It is common have variables appear both on the left hand side and right hand side of an operator
    • Example: x = x + 1
    • Example: total = total + number
    • Example: blanace = balance - withdrawal
  • This is so common that we have special statements for this


In [ ]:
# Let's re-write the examples
# Example: x = x + 1
x = 5
x += 1

# Example: total = total + number
total += number

# Example: balance = balance - withdrawal
balance -= withdrawal

Lab

  • Option 1. Work on an exercise.
  • Option 2. Work on your assignment.
  • Option 3. None of the above.

Exercise: Greatest Common Divisor

The greatest common divisor of two positive integers, n and m, is the largest number, d, that divides evenly into both n and m. Here is one algorithm to solve this problem.

Initialize d to the smaller of m and n While d does not evening divide m or d does not evening divide n do Decrease the value of d by 1 Report d as the greatest common divisor of n and m

Write a program that reads two positive integers from the user and uses this algorithm to determine and report their greatest common divisor.

Enter a positive integer: 5 Enter a positive integer: 10 The greatest common divisor of 5 and 10 is 5.


In [ ]: