ECS32A
Introduction to Programming
Fall Quarter 2023
Unit 2
First Programs
Dr. Kristian Stevens
“Programs do things with stuff”
-Mark Lutz
Learning Python
Printing to the Screen
ECS32A
Unpacking our First Line of Python
• The IDLE Python Shell window
• This is a statement executed
by the Python interpreter
• A statement is a unit of code
that has an effect, and this is
the result in blue
• print() is a built-in function
• does some computation (runs some code) on the input in the
parentheses.
• recognize a function by parentheses e.g. f(x)
• "Welcome" is a string. Strings are text (i.e. strings of letters).
• "42" and "9/7" would also be a strings
• Recognize a string by quotes.
Background Info - Why Types
Computers Represent Everything in Binary.
Binary numbers look like: 11010100
So how do we know what what this means?
Does that mean 11,010,100?
A different number?
Or a code for a letter?
These are conversion
charts from binary to
numerical values (Decimal)
and normal letters (ASCII).
You do not need to know or
memorize these yet, I have
included them only so you
can see how the binary
numbers can be
interpreted in different
ways, and why types
communicate to the
computer how to use a
binary value.
https://docs.python.org/3/library/stdtypes.html
"Strings" in English
"Strings" in Python
>>> print("Run away Spot.")
Run away Spot.
>>> print('Run, run, run.')
Run, run, run.
>>> print("You can't play here")
You can't play here
>>> print('You can't play here')
SyntaxError: invalid syntax
You can use either 'single' or "double" quotes.
If you want to print a quote or apostrophe be sure and
enclose them using the other type of quote. Fancy paired
quotes like “these” used for printed text won’t work!
(Try it)
Special Characters in Strings
>>> print("Go\nSpot\nGo")
Go
Spot
Go
>>> print("Go\tSpot\tGo")
Go Spot Go
Use \n to print a new line (return or enter key).
Use \t to print a tab (tab key).
These are called whitespace characters.
Why? Because in a book they print as the paper color.
(Try it)
Backslash vs. Forward slash
Used for the
Used for
special characters
division in Python
in strings.
/
\n and \t
Cow Joke
How would you print the joke in Python?
What's a cow's favorite holiday?
Moo years eve.
Can you do it using one line of code?
(Try it)
>>> print("What's a cow's favorite holiday?")
What's a cow's favorite holiday?
>>> print("Moo years eve.")
Moo years eve.
>>> print("What's a cow's favorite holiday?
\nMoo years eve.")
What's a cow's favorite holiday?
Moo years eve.
MOO
Can you print this? The cow said "MOO"
The print() function
• Syntax
print(value1,value2,…,valuen)
• The print function can be called with any number of input
values separated by commas
• If more than one value is given, the values are separated
by a space in the output.
• The output ends with a new line character "\n".
• All values are optional. If no input is given, a blank line is
printed.
Using print()
>>> print("Welcome\nto\nECS32A!")
>>> print("Welcome\nto\nECS32A!")
Welcome
to
>>> print()
ECS32A!
>>> print()
>>> print("Welcome","to","ECS32A!")
>>> print("Welcome","to","ECS32A!")
>>> print("The
Welcome to ECS32A!
answer is", 42)
>>> print("The answer is", 42)
>>> answer
The print("The
is 42
answer is", 6 * 7)
The print("The
>>> answer is 42answer is", 6 * 7)
The answer is 42
(Try it)
Values, Types
& Expressions
ECS32A
Python as a Calculator
Expressions in the IDLE Shell
• You can use the Python Shell window like a calculator
• You can use a print statement to print the value of an
expression in a program.
• The shell window will also print the value of an
expression just by itself.
Expressions and Operators
>>> print(4+5)
9
An expression is a short piece of code that can be reduced to a
value. In this example, 4+5 is an arithmetic expression with a
value of 9.
+ is the addition operator.
An operator does computation, like a function. The only reason
there are two ways to do computation (operators and functions) is
that it is more human-readable. The inputs are called operands.
There are also -, *, /, and ** for subtraction, multiplication
division and exponentiation.
Which is the
correct answer?
a) 1
b) 10
c) 16
d) none of the
above
Operator Precedence
• Why does this expression evaluate to 16?
8/2*(2+2)
• prec·e·dence (n)
priority in importance, order, or rank.
• Some operators are evaluated before others
• Otherwise we go left to right
Operator Precedence
• PEMDAS: Each category below is evaluated rst from left to
right before moving to the next.
• expressions in Parenthesis ( )
• Exponentiation **
• Multiplication and Division /,*
• Addition and Subtraction +,-
• If not obvious, parenthesize. You can always use
parentheses to explicitly de ne the order in which operators
are evaluated: (8/2)*(2+2) = 16.0 Expressions in nested
parentheses are evaluated rst: 8/(2*(2+2)) = 1.0
fi
fi
fi
Values and Types
Values and Types
• A value is one of the basic things a program
works with, like a number or some text.
• Values can be many different types of data, in
Python every value has a type.
• A type is a category, or class, of values that
determines how it is represented by the computer
and what we can do with it in our programs
• The types in Python we will discuss today are
strings, integers and oating point.
fl
Three Python Types
Three representations of the concept 42.
42 is an integer (whole number)
42.0 is a oating point (fractional number)
"forty two" is a string (text)
Data types are important because they determine what we
can do with the value. We can add integers and oating
point values but can’t add strings.
fl
fl
Integers
• Whole numbers are integers
• 1, 2, 5, 978787, 0, -100 are integers
• What about 8/3 or 0.6?
Floating point numbers
• 0.6, 7.34, and -2.0 are oating point numbers
• Division in Python 3 always evaluates to a oating point
• 7/2 produces the oating point value 3.5
• 6/3 produces the oating point value 2.0
• Addition, subtraction, and multiplication in Python 3
evaluate to a oating point when either operand is
oating point, so 7.0 + 3 produces the oating point
value 10.0.
fl
fl
fl
fl
fl
fl
fl
Example: Weight on the Moon
• Your weight on the Moon is approximately 1/6th your
weight on Earth. A person weighing 100 pounds on
Earth weighs 100/6 pounds on the Moon.
• The comma separated inputs to the print function can
be strings, integers, or oating point values. Nested
expressions are evaluated before the print function is
called.
>>> print("Weight on Earth:", 100)
Weight on Earth: 100
>>> print("Weight on the Moon:", 100/6)
Weight on the Moon: 16.666666666666667
fl
Floating point is not exact
>>> 100/6
16.666666666666667
>>> 100*(1/6)
16.666666666666665
• This is weird...why?
• Computer numbers have a xed number of
decimal places. They are represented by binary
integers under the hood.
• Exact results with oating point numbers would
have an in nite number of decimal places:
100/6 has the value 16.666666.......
fi
fl
fi
The type() function
The built-in type() function can be used in the
Python shell to get the type of a value.
>>> type('42')
<class 'str'>
>>> type(42)
<class 'int'>
>>> type(42.0)
<class 'float'>
For now think of this word 'class' in the sense of
de ning a class (or category) of Python values.
fi
Example: Calculating Tax and Tip
>>> print("Item:", "ramen")
Item: ramen
>>> print("Cost:", 10)
Cost: 10
>>> print("Tax:", 10 * 0.0825)
Tax: 0.8250000000000001
>>> print("Tip:", 10*0.2)
Tip: 2.0
>>> type("ramen")
<class 'str'>
>>> type(10)
<class 'int'>
>>> type(10 * 0.2)
<class 'float'>
(Try it)
Example: Parentheses Required?
3 × (4 − 5) >>> 3 * (4 - 5)
20 + 10
>>> (20 + 10) / 3
3
3 × 100 >>> (3 * 100) / 2
2
7 >>> 7 / (100 * 12)
100 × 12
(Try it)
Example: Parentheses Required?
3 × (4 − 5) >>> 3 * (4 - 5) Yes
-3
20 + 10 >>> (20 + 10) / 3 Yes
3 10.0
3 × 100 >>> 3 * 100 / 2 No
2 150.0
7 >>> 7 / (100 * 12) Yes
100 × 12 0.005833333333333334
Cheat Sheet
Variables
ECS32A
Variables
• We use named variables to store and reference stored
values in a program.
• An assignment statement creates a variable and gives
it a value, or updates the value of an existing variable.
>>> message = "Welcome to 32A"
>>> pi = 3.14
>>> x = 2
>>> print(x)
2
So x = 2 is not algebra! It is an assignment statement.
You can pronounce this "assign 2 to x" to avoid confusion.
Variables
• Metaphor:
x = 5
• Variables names refer to locations in memory that store
data. Python variables can hold any type of data.
• You can think of a variable as a box.
• The name x is the label on the box.
Assignment statement
x = 5
5 5
x
In an assignment statement, the box on the left of = is
lled with the value on the right. The value on the right
could be from an evaluated expression.
fi
Assignment statements create variables
x = 5
5
x
After the assignment statement is executed the
integer value 5 is now in the box. If the box
didn’t already exist, it would have been created.
The name of the variable is x and its value is 5.
Assignment Statements
y = x
5 5
y x
The expression on the right can be just another variable.
Here Python evaluates x and assigns it to y.
Of course, it doesn't make sense to do this until the
variable x is created, and Python will complain if you try.
Assignment Statements
x = 2
5
2 2 y
x
The original y is unchanged
if we assign another value to x value later
Common Assignment Statement
count = count + 1
This is a common pattern with assignment statements.
It’s also weird algebra!
So what does it do?
Assignment Statements
count = count + 1
2
3 count +1
Step 1:
Evaluate the expression on the right.
It evaluates to the integer 3
Assignment Statements
count = count + 1
2
3
count
Step 2:
Put the value 3 in the box named count.
This "kicks out" 2.
Assignment Statements
count = count + 1
3
count
After executing the statement:
The new value 3 is in the box named count.
The old value 2 was "kicked out" and is gone.
We say we incremented the variable count by 1.
Swapping Values
2 5
y x
How would we "swap" the values in two variables using
assignment statements?
Why won’t the two statements below work?
y = x
x = y
(Try it)
Swapping Values
y = x
x = y
5 5
y x
• After the rst statement is executed, we lose the value
that was stored in y.
• A third variable z can be used to temporarily store the
value being overwritten.
fi
Swapping Values
z = y
y = x
x = z
2
z
2 5
y x
We could call this juggling values
Swapping Values
z = y
y = x
x = z
2
z
5 5
y x
We could call this juggling values
Swapping Values
z = y
y = x
x = z
2
z
5 2
y x
We could call this juggling values
Swapping Values
z = y
y = x
x = z
2
z
5 2
y x
The values in x and y have successfully been swapped!
Naming Variables
• Use "meaningful" variable names.
• mnemonic means "memory aid"
• A mnemonic name helps you remember the role of
the variable when you are looking at the code.
• These statements are equivalent to the Python
interpreter, but not to a human interpreter
a = 35 meal_cost = 35
b = 0.2 tip_rate = 0.2
c = a * b tip = meal_cost * tip_rate
print(c) print(tip)
Naming Variables
• Use your own meaningful variable names!
• Variable names can only contain letters, numbers, and underscores,
but can’t begin with a number.
• Variable names cannot be Python keywords and shouldn’t be Python
function names (e.g. min, max). Usually these problems are detected
with syntax highlighting.
• Variable names can be arbitrarily long but programmers generally
constrain variable length for readability.
• Python is case sensitive. The convention is to begin variables in
lowercase, unless you want to indicate a constant using ALL CAPS.
• Bad variable names result in a "SyntaxError" message. These are usually
quick to nd and x. Misspelled variable names are common and they
result in a "NameError".
fi
fi
Compound Variable Names
Lower camel case (e.g. camelCase) is when subsequent
elements of compound words are capitalized.
Snake case (e.g. snake_case) is when elements of compound
words are separated with an underscore.
The only rule here is to be consistent within a program.
Valid Variables?
cats = 1
count1 = 2
number of cats = 3
cat-count = 4
numCats = 5
cat_number = 6
7cats = 7
CATS = 8
(Try it)
Valid Variables?
cats = 1 Yes
count1 = 2 Yes, numbers OK
number of cats = 3 No, spaces allowed
cat-count = 4 No, underscore only symbol
numCats = 5 Yes, this is camelCase
cat_number = 6 Yes
7cats = 7 No, begins with a number
CATS = 8 Syntax OK, but all caps
reserved for constants
Break
• https://amazingtimer.com/countdown_timer.php
Writing Programs
ECS32A
Terminology: Statement
A statement is a unit of code that the Python interpreter
can execute. It has an effect in a program, like creating
a variable or displaying a value.
We have seen print and assignment statements.
>>> x = "Welcome to ECS32A"
>>> print(x)
Welcome to ECS32A
Terminology: Expression
An expression is a combination of values, variables, and operators. It is
often shorter than a statement. An expression reduces to a single value. The
following are all expressions assuming that x has been assigned a value:
2
17
xx
x x ++ 117
If you type an expression in the shell window, the interpreter evaluates it
( nds the value) and displays the result:
>>> 1 + 2
3
But unlike a statement, an expression by itself doesn’t do anything in a
program. You need to do something with it like assign it to a variable.
fi
Writing Programs in IDLE
• A program is just a series of statements.
• To write a whole program in IDLE instead of single
lines in the shell window, we use the script window.
• A script is just another name for a program that is
run by an interpreter.
HW 1 Problem 1
(See the next few slides for how to type this in)
Making a program
• In IDLE start by selecting New File
Making a program
• Write a bunch of statements into the new script
window.
(Try it)
Making a program
• Run a program from the run menu
by selecting run module.
• Output will appear in a shell window.
(Try it)
ECS32A
Introduction to Programming
Spring Quarter 2023
Unit 2
First Programs
Continued
Dr. Kristian Stevens
Python Tutor
Program Output
Memory
Python Tutor: https://tinyurl.com/rkehapd
Python Tutor
Program Output
Memory
Python Tutor: https://tinyurl.com/rkehapd
Comments
Our temperature converter program with a new
language feature: comments.
Comments help us document code so that we
and others can understand it.
Comments
• Comments are a way to make notes in a program. They
allow us to explain some code in natural language
• Comments should document everything that is not obvious
• Comments begin with a hashtag #,
and everything after the # on a line
will be ignored by the Python interpreter.
v = 5.0 # velocity in meters/second.
v = 5.0 # assign 5 to v is a useless comment
Example Comments
• Comments can be on their own line proceeding a
statement
# the percentage of the hour that has elapsed
percentage = (minute * 100) / 60
• or at the end of the statement
v = 5.0 # velocity in meters/second.
• good variable names reduce the need for comments
Headers
• Headers are comments that go at the top of a script
# fahr2cel.py
# Author Name, Partner Name (optional)
#
# Homework assignment 1
# Convert degrees Fahrenheit to Celsius
Building Blocks of
Programs
ECS32A
Framework
Input Output
Get data from the Communicate
“outside world” results to the user
Sequential Execution
Perform statements one after another, in the
order they are written.
Conditional Execution Repeated Execution
Make decisions by checking conditions Perform statements repeatedly, usually
then execute or skip statements with variation
Code Reuse
Write a set of instructions once, and then
reuse those instructions as needed
throughout your program
Advanced Operators
ECS32A
The oor division // operator
Also known as integer division because result is rounded
down to the nearest integer. It doesn’t always result in an
integer type value.
>>> 42.0 // 10
4.0
>>> -42 // 10
-5
>>> minutes = 105
>>> hours = minutes // 60
>>> hours
1
fl
The modulus % operator
Divides two numbers and returns the remainder.
>>> minutes = 105
>>> remainder = minutes % 60
>>> remainder
45
Often used to quickly determine if one number evenly
divides another.
If x % y is zero then x is divisible by y.
If x % 2 is zero then x is even.
Example: Elapsed time
In this example we convert a long elapsed time
in minutes to a more user friendly representation.
total_minutes = 14290
total_hours = total_minutes // 60
remaining_minutes = total_minutes % 60
days = total_hours // 24
remaining_hours = total_hours % 24
print(days, "Days",
remaining_hours, "Hours",
remaining_minutes, "Minutes")
9 Days 22 Hours 10 Minutes
Python Tutor: https://tinyurl.com/y526ncvp
Advanced Operators
Continued
ECS32A
String Operators
You can’t perform math on strings, even when the strings look like
numbers! These expressions result in errors.
>>> "2"-"1"
File "<pyshell>", line 1, in <module>
"2"-"1"
TypeError: unsupported operand type(s) for -: 'str'
and 'str'
>>> "1"/"3"
File "<pyshell>", line 1, in <module>
"1"/"3"
TypeError: unsupported operand type(s) for /: 'str'
and 'str'
String Operators
The + operator on strings performs string concatenation. It
creates a new string from the end to end join of the two
strings being concatenated.
>>> "2"+"2"
'22'
>>> course = "ECS32A"
>>> print("Welcome to",course+"!")
Welcome to ECS32A!
String Operators
The * operator performs string repetition. It creates a
new string by concatenating an integer number of
copies of the string being repeated.
>>> "Spam"*4
'SpamSpamSpamSpam'
>>> 3 * "$"
'$$$'
See what happens if you try and multiply a string by a
oating point or another string.
fl
User Input
ECS32A
Temperature Converter
Our temperature converter generates output but does not
get input from the user.
We can give our programs exibility if we can get them to
accept and process different inputs.
fl
Getting input from the user
fahrenheit = input("Enter degrees Fahrenheit:")
• This is an assignment statement
• fahrenheit is a variable
• input() is a new function
• The value of the expression:
input("Enter degrees Fahrenheit:")
....will be whatever string the user types in as input.
The input() Function
fahrenheit = input("Enter degrees Fahrenheit:")
• The input() function will print a supplied string
prompting the user for input.
• The input() function then returns everything
typed at the keyboard (until the return or enter key
is pressed) as a single string.
• The input function always returns a string.
• The assignment statement assigns the string to the
variable on the left.
Adding user input to the temperature
converter
Do you see the problem here?
What happens if the user enters 42 as input?
(Try it)
TypeError
Python says it’s the wrong type!
It’s confusing at rst,
but embedded is the location and type of the error.
You can’t subtract a number from a string.
fi
Integers vs. Strings
The same concept can have multiple representations:
42 "42"
is an integer is a string
The data type determines what we can do with it.
We can convert from a string to an integer using int()
Corrected program
(Try it)
Introduction to Python’s
Built in Functions
ECS32A
Functions
• So far we have seen the print(), type(), input(),
and int() functions.
• Recognize a function by parenthesis.
• We said a function does some computation. Or more
formally, a function is a named sequence of statements.
Variables name data, functions name code. Functions are
like small programs with their own input and output.
• Functions are an example of code reuse.
• Use the help() function in the IDLE shell window to get more
info on how to use a function.
Function Terminology
• When we use a function, we say we call it.
• The inputs to the function are contained in the parentheses.
Multiple values are separated by commas.
• The inputs to a function are also called the function’s
arguments. We say the function takes an argument. In the
function code, the arguments are passed or handed off to
special variables used inside the function called parameters.
• If the function has output, we say the function returns a
value. The function call is replaced with the return value after
it is evaluated. The functions int(), and input()have
return values but print() does not. (Try it)
Type Conversion
Functions
Python type conversion
Python type conversion functions are always named
after the type they convert to:
• The int() function returns an integer
• The float() function returns a oating point
number
• The str() function returns a string
They should work for inputs that unambiguously
make sense.
fl
Converting to integer
x = int("42")
• int() converts the string "42" to the integer 42
• int() is a function
• It can take a string or a oating point as input.
• The value it returns is an integer.
fl
Converting to an integer with int()
>>> int("3")
3
>>> int(3.2)
3
>>> int(3.9)
3
>>> int("3.7")
File "<pyshell>", line 1, in <module>
int("3.7")
ValueError: invalid literal for int()
with base 10: '3.7'
With the last example, Python refuses to guess the
programmers intent.
Converting to oating point
x = float("3.2")
• float() converts the string "3.2" to the oating
point number 3.2
• float() is also a built-in function.
• It can take a string or integer value as input.
• The value it returns is a oating point.
fl
fl
fl
Converting to oating point with
float()
>>> float("3.2")
3.2
>>> float("3")
3.0
>>> float(3)
3.0
>>> float("three")
File "<pyshell>", line 1, in <module>
float("three")
ValueError: could not convert string to
float: 'three'
fl
Converting to a string with str()
>>> str(42)
'42'
>>> str(4.2)
'4.2'
>>> str("forty two")
'forty two'
>>> dollars = 42
>>> "$" + str(dollars)
'$42'
Useful when constructing strings using the + operator.
Example Programs
ECS32A
Parrot
This program simply echos user input
# parrot.py
#
# Echo user input
text = input("Enter some text:")
print("You entered '" + text + "'")
Enter some text:I can't think of anything.
You entered 'I can't think of anything.'
Python Tutor: https://tinyurl.com/y4q6rqkr
Check Splitter
Split the bill among friends
# split.py
#
# Check splitter
total = float(input("Total bill:"))
people = int(input("Number of diners:"))
share = total/people
print("Each person owes $" + str(share))
Total bill:100.98
Number of diners:3
Each person owes $33.660000000000004
Python Tutor: https://tinyurl.com/y6ou534x
Postage Stamp Machine
Simulate a postage stamp vending machine.
A customer inserts dollar bills into the vending
machine and then pushes a “purchase” button.
The vending machine vends the maximum
number of 55 cent rst-class stamps and then
returns the change.
Python Tutor: https://tinyurl.com/y5zaota8
fi
# stamps.py
STAMP_PRICE = 55 # First class
dollars = input("Enter number of dollars:")
dollars = int(dollars)
pennies = 100 * dollars
# Calculate number of stamps to vend
stamps = pennies // STAMP_PRICE
# Calculate change due using
# pennies - (stamps * STAMP_PRICE)
change = pennies % STAMP_PRICE
# Output result
print("First class stamps:", stamps)
print("Change:", change, "cents")