know the vocabulary (high level vs low level languages, etc.)
binary to decimal and back
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?
natural languages evolved organically, programming languages are usually synthetic and intentional
programming languages are usually unambiguous in meaning, while there is usually room for interpretation in natural languages
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?
values are just data
it can be stored in a variable
it can be computed in an expression
it can't be evaluated further (2 + 3 is not a value, because it can be evaluated further)
some examples of values:
-123456
"a string is a value"
1.00000001
True, False
Literals
The representation of a bare value in code is sometimes called a literal.
"a string " a string literal
254 - an integer literal
False - a bool 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. →
str (string) - "yup, a string"
bool (boolean value) - True
int (integer) - 12
float (floating point) - 12.121212
complex (complex numbers) - 1j * 1j (just know that this exists; it won't be in the exam)
range (an arithmetic sequence of numbers)
Strings, Integers and Floating Point Numbers
Strings
a string is a sequence of characters (any characters).
including spaces and punctuation
and by spaces, I mean spaces, tabs, newlines, etc
for example " " is a string!
so is "" (this, however, is an empty string)
are delimited by quotation marks - must start and end with quotes!
(btw, a delimiter is just a character or characters that marks a boundary… or distinguishes a value from other values)
for example "foo", 'bar', and """baz""" are all 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
if you don't have matching start and end quotes (unbalanced quotes)
if you forget to close your quotes (you have a start quote, but no end)
… you'll also get a syntax error
There Are Three Ways to Quote Strings
What are the three ways to quote strings?
double quotes - "
single quotes - '
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?
single or double quotes allow you to put in single or double quotes into a string without needing to escape them
"I'm"
'use a " to delimit a string'
triple double quotes allow you to span multiple lines (you can't span multiple lines with single or double quotes)
Constructing Strings / String Operators
So far, we've seen a couple of methods of putting strings together. What are they? →
string concatenation - adding two strings together using the + symbol
concatenation gives back a string
string formatting - creating a string with place holders where variables are plugged in
What's String Concatenation?
String concatenation works intuitively. Describe what it is. →
+ adds two strings together
both arguments must be strings
if an operand is not a string, convert it to one using str
# 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=314pet="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 "*3print(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? →
+ - concatenation - takes two strings (error otherwise) → returns a string
% - formatting - takes a string on the left and a comma separated list of values on the right
* - 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? →
we can use the backslash character before the special character
for quotes, we can use mixed quotes (embed single quotes in a double quoted string)!
we can also create newlines using \n
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?
prefixed with the # token (either before code or on the same line after code
or surrounded by triple double quotes as a bare string literal
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.
ints and floats are just numbers
(no quotes needed… though a decimal point will automatically make a value into a float)
however - Don't use commas! They don't mean what you expect. →
sometimes ints and floats can be expressed with scientific notation (though we won't cover this in the exam)
Integers
int - integers
whole number - negative or positive
examples: 1751, -95
"unlimited" (arbitrarily high)
Floating Point Numbers
float - floating point numbers
real number - contains decimal point
10.00, 491.545532111
may overflow
small and large numbers expressed in scientific notation (though we won't cover this in the exam)
Operators
addition, multiplication and subtraction: +, *, and -
division: / (results in a float even if two integers - ex 10 / 2 → 5.0)
integer division: // (next integer to the left - ex -23 // 3 → -8)
modulo: % (ex 10 % 7 → 3)
exponentiation: ** (ex 2 ** 3 → 8)
Numeric Operator Precedence
What order are these numeric operators evaluated in? →
most of these numeric operators will only work with numeric types (float, int)
if you try to add, subtract, divide with an numeric type and a string, you will get an error
always use int() or float() to convert your string to a numeric type if you're going to do calculations
Results of the Following Operations
What are the resulting values and types after evaluating the following expressions? →
28 / 7
28 // 10
28 % 10
28 / "7"
4.0 - float
2 - int
8 - int
Error
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 →
importmathx,y=8,6# you can also use (some value) ** 0.5h=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 + 5a=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. →
True or False
note the uppercase 'T' and 'F'
just like other values, can be assigned to variables
bools can be combined into expressions using logical operators
Range Objects
One last type / class / kind of data that we've encountered was a range object. Describe what a range object is. →
range objects represent an arithmetic sequence.
they are iterable and can be used to drive a for loop
they are created using the range function
A Guessing Game
1
1.0
"1"
"""1.0"""
1.111
'1,111'
True
range(5)
1 + 5
"hello" + " my friends!!!"
A Guessing Game (Answers)
1 - int
1.0 - float
"1" - str
"""1.0""" - str
1.111 - float
'1,111' - str
True - bool
range(5) - range object
1 + 5 - int
"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!
int()
str()
float()
bool()
range() is special in that it can take 1, 2 or 3 parameters to create a range object.
Conversion Functions Continued
note that int() and float() will only accept int and float "like" values… "5" will be converted (even with spaces), but "five" will cause an error
these can be used to avoid errors when using numeric or string operators
num=99print(str(num)+" red balloons")
remember - you don't have to convert if your value is already the type you're converting to
num="99"# no need to convertprint(num+" red balloons")
Other Built-In Functions
Name some built-in functions! →
print - outputs value to screen; returns nothing
input - prompts user for input; returns a str
type - returns the type of the value passed in; returns a type object
round - rounds a number; returns an int (when called with one argument) …(we used this in a homework)
abs - absolute value; returns a numeric type
obv, all of the conversion functions
A Word About input
it takes one argument… which is what gets displayed to the user (the prompt)
the program will wait until the user provides input
input returns a string that represents the user's input
even if the input looks numeric (say 234)
it still returns a string (in the previous case "234")
Variables and Variable Naming
Variables
variable - name that refers to a value
this terminology is important; very specific… name and value
we can now use that name instead of the explicit value
the equals sign, = is the assignment token or assignment operator that we use to bind a name to a value
name on left
value on right
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
you can reassign or rebind
let's see that in action →
>>> 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
you can make them as long as you want… though I suppose it could crash your computer
names can only consist of numbers, letters and/or underscores
the first character has to be a letter or an underscore
case sensitive - case matters
the name can't be a keyword or reserved word
Am I a Valid Name?
Are these valid variable names? →
_foo
1_foo
foo
1foo
$foo
foo$
Am I a Valid Name (Answers)?
Are these valid variable names? →
_foo - yes
1_foo - no
foo - yes
1foo - no
$foo - no
foo$ - no
Comparison Operators, Boolean Operators
Comparison Operators
Name six comparison operators?→
== - equals (can be called logical equivalence or equality operator)
!= - not equal
> - greater than
< - less than
>= - greater than / equal
<= - less than / equal
Comparison Operators Continued
again - these operators always return a bool
these operators do what you would expect
== - returns True if both sides are equal →
!= - returns True if both sides are not equal →
>, <, >=, <= - returns True if value on the left is greater than, less than, greater than / equal, or less than equal to the value on the right →
remember that the equal sign is always second for these operators >=, <=
Comparison Operators and Different Types
objects of different types, except different numeric types, are never equal
equals (==) will always return False for different types →
not equals (!=) will always return True for different types →
the <, <=, > and >= operators…
will raise a TypeError if the objects are of different types that cannot be compared →
will happily compare numeric types (for example comparing floats and ints works as you'd expect)! →
What are Logical Operators?
Logical Operators are operators that combine Boolean values.
always return another Boolean value.
can be used to create more complex Boolean expressions.
Three Logical Operators:
Name 3 logical operators, how many operands they take, and what operands they need to return True. →
and -
takes two operands, one on each side
to return True, both sides of the operator must evaluate to True →
or -
takes two operands, one on each side
to return True,at least one side of the operator must evaluate to True →
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
True and False →
True and not False →
True or False →
True or not False →
False or False →
not False and not False →
Chaining Boolean, Comparison, and Other Operators
You can chain together operators to make complex Boolean expressions!
Boolean expressions can involve Boolean, comparison, and other operators
numeric / string operations (in turn, are also ordered)
comparison operations (==, !=, >, <, >=, >=)
not
and
or
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"
begin with keyword if
condition
colon - ends the condition / marks that a block of code is about to come up
if + condition + colon usually is considered the if-statement header
body of if statement ends when indentation goes back one level
blank lines don't count as ending a block of code!
Let's See That Again
a,b="foo","bar"ifa!=b:# totally ok? yes!# but why?# perhaps when done more reasonably, readabilityprintaprintaprintbprintb
Oh Yeah, Else What?
We can use else to execute code if the original condition was not met
go back one level of indentation to mark that the previous code block has ended
keyword else
body - indented, body ends when indentation goes back one level
not required, obvs
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> ")ifanswer=='yes':print("Here, have some cake.")ifanswer=='no':print("No cake for you.")ifanswer!='yes'andanswer!='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
if statement like usual
go back one level of indentation to mark that the previous code block has ended
keyword elif
condition
colon
body - indented, body ends when indentation goes back one level
not required obv
even if more than one true, only the first true executes!
can add an else at the end
elif Example
How would we redo the cake exercise with elif? →
answer=input("Do you want cake?\n> ")ifanswer=='yes':print("Here, have some cake.")elifanswer=='no':print("No cake for you.")else:print("I do not understand.")
How to Order Conditions
if more than one condition in a series of elif's is true
only the first true condition is executed!
other are skipped, including else
ordering conditions so that the broadest ones are evaluated last may help avoid this issue
be careful of conditions that never get evaluated
an above condition may already account for it
here's an example…
How to Order Conditions Continued!
Here's a contrived exercise:
determine whether a number is 101 or if it's greater than 100
if it's 101, it should only print out that it's "exactly 101" (it shouldn't print out greater than 100)
Here's an implementation. What gets printed if n = 200? What gets printed if n = 101? →
ifn>100:print("more than 100")elifn==101:print("exactly 101")
answer=input("Do you want cake?\n> ")ifanswer=='yes':print("Here, have some cake.")ifanswer=='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
it behaves as you'd expect
remember to get indentation right
if there are multiple elif's or else's, you can use indentation to see which initial if statement they belong to
this works for any combination of if, elif and else
note that sometimes nested if statements are equivalent to and
best to simplify - that is, less nesting, better
Nested If Statements and And
How would you simplify this? →
a=100ifa>25:ifa<200:print("I'm in here")print("We're out there")
a=100ifa>25anda<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> ")ifanswer=='yes':print("Here, have some cake.")else:ifanswer=='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? →
math
random
sys (we didn't realize use sys that much, though…)
So… What Can These Modules Do?
math
pi - a constant that contains the value of pi→
floor(x) - returns the smallest integer less than or equal to x→
ceil(x) - returns the smallest integer greater than or equal to x→
sqrt(x) - returns the square root of x→
cos(x) - returns the cosine of x radians →
So… What Can These Modules Do (Continued)?
random
random() - return a random float that's between 0 and 1→
randint(a, b) - returns a random int that's a <= n <= b→
sys
exit([arg])_ - exits form python→
version - a constant that contains the version of Python→
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: 0Numbers summed: 0Please enter a number to add> 10Do you want to continue adding numbers (yes/no)?> yesCurrent total: 10Numbers summed: 1Please enter a number to add> 12Do you want to continue adding numbers (yes/no)?> noThe average is 11.0
A Potential Solution
total=0count=0answer='yes'print("I'll calculate the average for you!")whileanswer=='yes':print("Current total: "+str(total))print("Numbers summed: "+str(count))total=total+int(input("Please enter a number to add\n> "))count=count+1answer=input("Do you want to continue adding numbers (yes/no)?\n> ")print("The average is "+str(total/count))
Other While Loop Exercises
simulate a blackjack AI by continuing to hit until some threshold that's close to 21
a number guessing game
rock paper scissors until # of wins is greater than 0
simulate password protection
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.→
importrandomones=0forcountinrange(1,1000):roll=random.randint(1,6)ifroll==1:ones=ones+1print(str(ones)+" of 1000 rolls were ones")
Other For Loop Exercises
sing 99 bottles of beer!
number guessing game with limited number of guesses (use break for win!)
input that affects range… say hello x number of times…
For Loops…
When should you use them? →
you know ahead of time how many iterations you'll have to go through
you have to go through every element in an iterable object
every number in a sequence of numbers
every item in a list
every character in a string
While Loops
When should you use them? →
when you don't know how many iterations you'll have to go through!
when you must repeat something until some condition is met
generally not a great option for counting (need to keep track of counter separately)
Let's Try Using Both…
count to 0 to 25 by 5's
implement using while
implement using for
print out a series of numbers, each randomly chosen from (1 through 10) that add up to 50 (you can go over)