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
use keyword arguments to define the separator between arguments and the character that gets printed at the end
Format Function
The format function takes 2 arguments:
the value to be formatted
the format specifier (a string)
The format function returns a string
Format Function contintued
The syntax for the second argument, the format specifier is as follows:
some flags we used were > and < to specify where padding would be placed… and , to specify that a comma should be included
width is the total width (number of characters returned)
. and precision for number of decimal places
type… which is the type of the value that we're expecting to format
Types for Formatting
These are some of the possible types that we can use in our format specifier:
d - integer
f - float
s - string
% - percent
If the type you specify does not match the type of the value of the first argument, you'll get an error.
Format Examples
Intro to Programming
Introductory Material
mostly for short answer questions
read the slides from the first class
…as well as the first chapter
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. →
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 - """
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
String Formatting
What is string formatting? →
Allowing placeholders in a string to accommodate variable / value substitution by using the % operator.
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!)
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
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: →
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 →
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…
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
remember - you don't have to convert if your value is already the type you're converting to
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
Assignment vs Equality
Don't confuse the assignment operator with the equality operator! What's the difference between the two? →
Reassignment / Rebinding
you can reassign or rebind
let's see that in action →
While We're on the Subject… Multiple Assignment
You can assign multiple variables in one line.
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
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? →
Truth Table - OR
Let's fill out a truth table for or! →
How About Something More Complicated?
Let's fill out a truth table for p and not q and r! →
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
print out 1 to 100 …with the following exceptions:
for multiples of three, print out "Fizz" instead of the number
for multiples of five, print out "Buzz" instead of the number
for multiples of both three and five print “FizzBuzz”
example output, next slide, plz!
FizzBuzz Output
FizzBuzz Solution
Another Gotcha!
Will this code work?? →
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? →
Nested If Statements Example
We could have impemented the cake exercise using nested if statements. →
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→
A Potential Solution
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.→
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)