DS2000 (Spring 2019, NCH) :: Lecture 2a

0. Administrivia

  1. Wednesday (in Practicum): first in-class quiz (via Blackboard; no book/notes/Python)
  2. Due Friday @ 9pm: first homework (submit via Blackboard)
  3. New website reference: class Python reference (list of everything we've covered)

1. One More Data Type

What types have we talked about?

In [2]:
ourtypes = ["string", "int", "float", "list"]

How do we represent the result of yes/no questions? For example, the MOST important question in any class...

In [3]:
mygrade = 92.1
print(mygrade)

do_i_have_an_A = mygrade >= 94
print(do_i_have_an_A)
print(type(do_i_have_an_A))
92.1
False
<class 'bool'>

A Boolean variable can represent two values: True/False

Some useful comparison operators...

In [4]:
print(mygrade < 94) # all combinations of >/< with/without =
print(mygrade == 94) # are they equal (notice different from =, which is assignment)
print(mygrade != 94) # NOT equal (in general the BANG, !, means NOT)
True
False
True

A useful operator when it comes to lists and strings (and other types to come!)...

In [5]:
print("boolean" in ourtypes)
ourtypes.append("boolean")
print("boolean" in ourtypes)

print("i" in "team")
False
True
False

We can also combine boolean expressions together with logical operators...

In [6]:
print(not ("i" in "team")) # True becomes False, False becomes True

print(("m" in "team") and ("e" in "team")) # True if all are True, False otherwise
print((mygrade < 94) and (mygrade >= 90))

has_a_vowel = ("a" in "team") or ("e" in "team") or ("i" in "team") or ("o" in "team") or ("u" in "team")
print(has_a_vowel) # True if any are True, False otherwise
True
True
True
True

2. Conditional Execution

Boolean expressions are particularly useful when you want Python to do something if a particular condition holds...

In [10]:
myfavoritenumber = 7
guess = int(input("Guess a number: "))

if myfavoritenumber == guess:
    print("Wow!")
print("(Most Amazing) Game Over")
Guess a number: 7
Wow!
(Most Amazing) Game Over

Frequently we want the ability to express what happens if the condition does not hold, so we can optionally provide an else clause...

In [11]:
if myfavoritenumber % 2 == 0:
    print("Hint: it's even")
else:
    print("Hint: it's odd")
Hint: it's odd

You can do more than one thing within one/both clauses...

In [15]:
if myfavoritenumber % 2 == 0:
    print("Hint: it's even")
    print("and when you add 5 you get {}".format(myfavoritenumber + 5))
else:
    print("Hint: it's odd")
    print("and when you subtract 1 you get {}".format(myfavoritenumber - 1))
    if myfavoritenumber > 0:
        print("and it's positive")

print("\nHave you figured it out yet???!!") # \n produces a new line
Hint: it's odd
and when you subtract 1 you get 6
and it's positive

Have you figured it out yet???!!

Frequently we also want a sequence of questions...

In [20]:
myfavoritelanguage = "English"

if myfavoritelanguage == "English":
    print("Well that's boring...")
elif myfavoritelanguage in ["French", "Spanish", "German"]:
    print("Classic")
elif myfavoritelanguage == "Python":
    print("Well said :)")
else:
    print("Mysterious!")
Well that's boring...

Just be careful...

In [22]:
if myfavoritelanguage == "English":
    print("Well that's boring...")
if myfavoritelanguage in ["French", "Spanish", "German"]:
    print("Classic")
elif myfavoritelanguage == "Python":
    print("Well said :)")
else:
    print("Mysterious!")
Well that's boring...
Mysterious!

Exercise: ask person 1 for three hobbies, then ask person 2 for three hobbies, and finally output how many they have in common.

In [23]:
hobbies1 = input("Person 1! Please enter 3 hobbies (separated by ,): ").split(",")
hobbies2 = input("Person 2! Please enter 3 hobbies (separated by ,): ").split(",")

in_common = 0

if hobbies1[0] in hobbies2:
    in_common += 1 # x += y is just short for x = x + y
    
if hobbies1[1] in hobbies2:
    in_common += 1 # x += y is just short for x = x + y

if hobbies1[2] in hobbies2:
    in_common += 1 # x += y is just short for x = x + y

word = "hobbies"
if in_common == 1:
    word = "hobby"

print("You have {} {} in common.".format(in_common, word))
Person 1! Please enter 3 hobbies (separated by ,): climbing,running,programming
Person 2! Please enter 3 hobbies (separated by ,): climbing,reading,knitting
You have 1 hobby in common.

3. Looping

That last problem was rather annoying... what if there had been 10 or 100 hobbies!? (Or what if we didn't know how many!?)

Looping is an instruction for Python to do something over and over.

The for loop says to perform a sequence of operations for each element in a collection (e.g., list, string)...

In [24]:
for num in [1, 2, 3]:
    print(num)
1
2
3
In [26]:
for number in [1, 2, 3]:
    if number % 2 == 0:
        print("{} is quite odd!".format(number))
    else:
        print("{} is even keeled".format(number))
    
    print("I'm so funny :)\n")
1 is even keeled
I'm so funny :)

2 is quite odd!
I'm so funny :)

3 is even keeled
I'm so funny :)

In [27]:
counter = 1
for letter in "word":
    print(letter * counter)
    counter += 1
w
oo
rrr
dddd

So now back to our hobbies...

In [28]:
hobbies1 = input("Person 1! Please enter your hobbies (separated by ,): ").split(",")
hobbies2 = input("Person 2! Please enter your hobbies (separated by ,): ").split(",")

in_common = 0

for hobby1 in hobbies1:
    if hobby1 in hobbies2:
        in_common += 1

word = "hobbies"
if in_common == 1:
    word = "hobby"

print("You have {} {} in common.".format(in_common, word))
Person 1! Please enter your hobbies (separated by ,): running,climbing,arithmetic
Person 2! Please enter your hobbies (separated by ,): reading,writing,sleeping,boxing,cooking,climbing
You have 1 hobby in common.