Midterm #1 Review

About These Slides

The first slides on formatting summarize the syntax of the format specifier and using print to format.

The remainder of the slides are just parts of all of the previous slides stitched together.

Formatting With Print

print('foo', 'bar', 'baz', sep=",", end="x")

Format Function

The format function takes 2 arguments:

The format function returns a string

Format Function contintued

The syntax for the second argument, the format specifier is as follows:

[flags][width][.precision]type 

Types for Formatting

These are some of the possible types that we can use in our format specifier:

If the type you specify does not match the type of the value of the first argument, you'll get an error.

format("2", ',d')
#   ValueError: Unknown format code 'd' for object of type 'str'

Format Examples

>>> format("2", '>10s')
'         2'
>>> format("hello", '>10s')
'     hello'
>>> format("hello", '<10s')
'hello     '
>>> format(2000.213, ',.1f')
'2,000.2'
>>> format(2000.213, '>20,.1f')
'             2,000.2'
>>> format(.2199, '.2%')
'21.99%'

Intro to Programming

Introductory Material

Programs and Languages

Define: program

A sequence of instructions that specifies to a computer actions and computations to be performed

List 3 differences between programming languages and natural languages?

  1. natural languages evolved organically, programming languages are usually synthetic and intentional
  2. programming languages are usually unambiguous in meaning, while there is usually room for interpretation in natural languages
  3. programming languages are generally more dense; every character is meaningful

Binary, Bits, and Bytes

What are the possible values that a bit can hold?

0 and 1

How many bits are in a byte?

8

What is 00001111 in decimal?

15

What is 2 in binary _ _ _ _ _ _ _ _ ?

00000010

More About Programming Languages!

What does a compiler do?

It translates a high-level programming language into a low-level language that the computer can execute (our books call this object code)

What's the difference between compiled and interpreted languages?

Languages that have an explicit compilation step are generally thought of as compiled languages. That is, the workflow for a compiled language is: write code, compile, execute… rather than just write code and then execute.

Tools

What's the name of the language we're using?

Python

What version of Python are we using?

3

Is python a high level or low level language? Why?

Python is a high-level programming language; it's meant to be easy to read and write for humans …

Tools Continued

What extension is used for Python source code files?

.py

What is the name of the text editor / IDE that we use?

We're using IDLE as our IDE

In IDLE, what's the difference between using the text editor and the interactive shell to execute code?

The interactive shell executes code as you enter each line; it give you immediate feedback. For a text editor, you have to save your entire program first before you can run it.

Values and Types

What are Values?

Literals

The representation of a bare value in code is sometimes called a literal.

Values can be Classified by Data Type

A data type is a set of values. The type of a value determines how it can be used in expressions. Sometimes data type is also referred to as just type… or class. Name as many types as you can.

  1. str (string) - "yup, a string"
  2. bool (boolean value) - True
  3. int (integer) - 12
  4. float (floating point) - 12.121212
  5. complex (complex numbers) - 1j * 1j (just know that this exists; it won't be in the exam)
  6. range (an arithmetic sequence of numbers)

Strings, Integers and Floating Point Numbers

Strings

Unbalanced Quotes

I'm sure you know by now what happens if you have an extra quote or a missing quote. →

>>> "oops " I quoted again"
SyntaxError: invalid syntax

There Are Three Ways to Quote Strings

What are the three ways to quote strings?

  1. double quotes - "
  2. single quotes - '
  3. triple double quotes for multiline strings - """
"double quoted string"
'single quoted string'
"""more than
one line.  omg!"""

When Would You Use One Over the Other?

Constructing Strings / String Operators

So far, we've seen a couple of methods of putting strings together. What are they?

What's String Concatenation?

String concatenation works intuitively. Describe what it is.

#  syntax error
"lucky number " + 9

#  will work fine
"lucky number " + str(9)

String Formatting

What is string formatting?

Allowing placeholders in a string to accommodate variable / value substitution by using the % operator.

greeting = "Hi.  My name is %s and I have %s %s"
name = "Joe"
number_of_pets = 314
pet = "aardvarks"
result = greeting % (name, number_of_pets, pet)
print(result)

String Multiplication

You can also use the * operator to multiply a string by an int (note that this will give an error if you use a float instead of an int!)

s = "aardvark " * 3
print(s)
#  prints out: aardvark aardvark aardvark  

String Operators at a Glance

These are the string operators that we learned (note - they all return strings, but the types of arguments may vary depending on operator). What were they again? →

  1. + - concatenation - takes two strings (error otherwise) → returns a string
  2. % - formatting - takes a string on the left and a comma separated list of values on the right
  3. * - multiplication - takes a string and int (error otherwise, even if it's another numeric type), repeats the string that number of times → returns a string

One Last Thing Regarding Strings (Escape!)

What do we do if we need a character that has special meaning in a string, such as a single or double quote?

print("escaping using \"backslash\"")
print("single  quotes ''''") 
print("""some "double quotes"""")

BTW, Does Anyone Remember Comments?

What are the two ways that we can write in a comment?

These are both comments: →

counter = 5     # this is a comment that's on the same line as code
"""
this one
is a comment too
"""

ints and floats

Integers and floating point numbers are both numeric types.

Integers

int - integers

Floating Point Numbers

float - floating point numbers

Operators

Numeric Operator Precedence

What order are these numeric operators evaluated in? →

>>> (5 + 15) * 2 ** 2 + 20
100

Numeric Operators and Type Compatibility

Results of the Following Operations

What are the resulting values and types after evaluating the following expressions? →

Implementing a Formula

An obvious use case for these numeric operations is implementing a formula.

For example: find the hypotenuse of a right triangle using this formula… h = √(x² + y²), where x is 8 and y is 6 →

import math
x, y = 8, 6
#  you can also use (some value) ** 0.5
h = math.sqrt(x ** 2 + y ** 2)

A Shortcut

There's a shortcut to add a value to an existing variable (the same exists for subtraction as well). What is the syntactic sugar that we use to increment and decrement variables?

-= and += are shortcuts for decrementing or incrementing a variable…

a = 0

#  increment a by some value, just set the variable, a, equal to a + 5
a = a + 5

#  or... alternatively, use a shortcut +=:
a += 5

Bools and Range Objects

The bool Type

Python has a bool type to represent Boolean values. Tell me everything you know about the bool type.

Range Objects

One last type / class / kind of data that we've encountered was a range object. Describe what a range object is.

A Guessing Game

  1. 1
  2. 1.0
  3. "1"
  4. """1.0"""
  5. 1.111
  6. '1,111'
  7. True
  8. range(5)
  9. 1 + 5
  10. "hello" + " my friends!!!"

A Guessing Game (Answers)

  1. 1 - int
  2. 1.0 - float
  3. "1" - str
  4. """1.0""" - str
  5. 1.111 - float
  6. '1,111' - str
  7. True - bool
  8. range(5) - range object
  9. 1 + 5 - int
  10. "hello" + " my friends!!!"

Built-in Functions

Conversion Functions

For each type that we learned, there's a function with the same name that will create a value of that type. They always return their associated type!

range() is special in that it can take 1, 2 or 3 parameters to create a range object.

Conversion Functions Continued

num = 99
print(str(num) + " red balloons")
num = "99" # no need to convert
print(num + " red balloons")

Other Built-In Functions

Name some built-in functions!

A Word About input

Variables and Variable Naming

Variables

some_variable_name = "a value"

Assignment vs Equality

Don't confuse the assignment operator with the equality operator! What's the difference between the two?

#  one equal sign is assignment
a = 1  

#  two equal signs mean test for equality
a == 1

Reassignment / Rebinding

>>> a = 23
>>> a
23
>>> a = "foo"

While We're on the Subject… Multiple Assignment

You can assign multiple variables in one line.

>>> a, b = 50, 60
>>> a
50
>>> b
60

Naming Variables

Am I a Valid Name?

Are these valid variable names? →

Am I a Valid Name (Answers)?

Are these valid variable names? →

Comparison Operators, Boolean Operators

Comparison Operators

Name six comparison operators?→

Comparison Operators Continued

Comparison Operators and Different Types

What are Logical Operators?

Logical Operators are operators that combine Boolean values.

Three Logical Operators:

Name 3 logical operators, how many operands they take, and what operands they need to return True.

  1. and -
    • takes two operands, one on each side
    • to return True, both sides of the operator must evaluate to True →
  2. or -
    • takes two operands, one on each side
    • to return True,at least one side of the operator must evaluate to True →
  3. not -
    • only takes one operand to the right
    • to return True, the original value on the right must evaluate to False →
    • two nots cancel eachother out (fun!) →

Logical Operators in Action

>>> True and False
False
>>> True and True
True
>>> True or False
True
>>> not True
False
>>> not not True
True

Truth Table - AND

and takes two operands. Each operand can be True or False (or will evaluate to True or False!).

Can you guess how many possible combinations ther are for these two operands? What will the Truth Table look like?

"""
(using p and q to represent the operands
...and t and f for true and false)
 p | q | p and q
----------------
 f | f | f
 f | t | f
 t | f | f
 t | t | t
"""

Truth Table - OR

Let's fill out a truth table for or! →

"""
(using p and q to represent the operands
...and t and f for true and false)
 p | q | p or q
----------------
 f | f | f
 f | t | t
 t | f | t
 t | t | t
"""

How About Something More Complicated?

Let's fill out a truth table for p and not q and r! →

"""
(using p and q to represent the operands
...and t and f for true and false)
 p | q | r | p and not q and r
-----------------------------
 t | t | t | f
 t | t | f | f
 t | f | t | t
 t | f | f | f
 f | t | t | f
 f | t | f | f
 f | f | t | f
 f | f | f | f
"""

Let's Evaluate Some Simple Boolean Expressions

Chaining Boolean, Comparison, and Other Operators

You can chain together operators to make complex Boolean expressions!

What do you think this evaluates to?

-10 ** 2 <= -100 or "foo" == "bar" and 100 >= 100
True

Order of Operations / Operator Precedence

A summary can be found in the official documentation for Python 3, but here's the short version:

Conditionals

Anatomy of an If Statement

Write an if statement testing if a and b are not equal. If they're not equal, print the value of a and b twice.

a, b = "foo", "bar"

Let's See That Again

a, b = "foo", "bar"
if a != b:
	# totally ok?  yes!
	# but why?
	# perhaps when done more reasonably, readability
	print a
	print a


	print b

	print b

Oh Yeah, Else What?

We can use else to execute code if the original condition was not met

What About Multiple Chained Conditions?

What if else is not fine-grained enough? For example, how about a program that asks for cake and handles a yes, no, or anything other than…

"""
Do you want cake?
> yes
Here, have some cake.

Do you want cake?
> no
No cake for you.

Do you want cake?
> blearghhh
I do not understand.
"""

Consecutive Ifs

One way to do it is consecutive if statements…

answer = input("Do you want cake?\n> ")
if answer == 'yes':
        print("Here, have some cake.")
if answer == 'no':
        print("No cake for you.")
if answer != 'yes' and answer != 'no':
        print("I do not understand.")

Else If (elif)

We can use elif to chain a series of conditions, where only one path of code will be executed

elif Example

How would we redo the cake exercise with elif?

answer = input("Do you want cake?\n> ")
if answer == 'yes':
        print("Here, have some cake.")
elif answer == 'no':
        print("No cake for you.")
else:
        print("I do not understand.")

How to Order Conditions

How to Order Conditions Continued!

Here's a contrived exercise:

Here's an implementation. What gets printed if n = 200? What gets printed if n = 101?

if n > 100:
	print("more than 100")
elif n == 101:
	print("exactly 101")

Ordering and Fizz Buzz

FizzBuzz Output

1
2
Fizz
4
Buzz
Fizz
.
.
14
FizzBuzz
16
.
.
98
Fizz
Buzz

FizzBuzz Solution

for i in range(1, 101):
	if i % 3 == 0 and i % 5 == 0:
		print("FizzBuzz")
	elif i % 3 == 0:
		print("Fizz")
	elif i % 5 == 0:
		print("Buzz")
	else:
		print(i)

Another Gotcha!

Will this code work??

answer = input("Do you want cake?\n> ")
if answer == 'yes':
        print("Here, have some cake.")

if answer == 'no':
        print("No cake for you.")
else:
        print("I do not understand.")

It does something unexpected! If the user enters yes, we get both "Here, have some cake" and "I do not understand." Be careful when using consecutive ifs

Nesting If Statements

Nested If Statements and And

How would you simplify this? →

a = 100
if a > 25:
	if a < 200:
		print("I'm in here")
print("We're out there")
a = 100
if a > 25 and a < 200:
	print("I'm in here")
print("We're out there")

Nested If Statements Example

We could have impemented the cake exercise using nested if statements.

answer = input("Do you want cake?\n> ")
if answer == 'yes':
    print("Here, have some cake.")
else:
    if answer == 'no':
        print("No cake for you.")
    else:
        print("I do not understand.")

Modules

We Looked at 3 Modules

What are some modules we've used, and what do they do? →

So… What Can These Modules Do?

So… What Can These Modules Do (Continued)?

Iteration

Sample While Loop

Write a program that continually asks the user for numbers, and asks them if they'd like to keep going. In the end, it should output the average of all of the numbers entered→

I'll calculate the average for you!
Current total: 0
Numbers summed: 0
Please enter a number to add
> 10
Do you want to continue adding numbers (yes/no)?
> yes
Current total: 10
Numbers summed: 1
Please enter a number to add
> 12
Do you want to continue adding numbers (yes/no)?
> no
The average is 11.0

A Potential Solution

total = 0
count = 0
answer = 'yes'
print("I'll calculate the average for you!")
while answer == 'yes':
        print("Current total: " + str(total))
        print("Numbers summed: " + str(count))
        total = total + int(input("Please enter a number to add\n> "))
        count = count + 1
        answer = input("Do you want to continue adding numbers (yes/no)?\n> ")
print("The average is "+ str(total / count))

Other While Loop Exercises

Counting Dice (For Loop Example)

Roll a die 1000 times; count how many times a one is rolled! Print out the result. Use a for loop.→

import random
ones = 0
for count in range(1, 1000):
	roll = random.randint(1, 6)
	if roll == 1:
		ones = ones + 1
print(str(ones) + " of 1000 rolls were ones")

Other For Loop Exercises

For Loops…

When should you use them? →

While Loops

When should you use them? →

Let's Try Using Both…