A value (object) is one of the fundamental things — like a word or a number — that a program manipulates.
Objects are classified into different classes, or data types.
Every object has an identity, a type and a value.
print(type("Hello, World!"))
print(type(17))
print("Hello, World!")
print(type(3.2))
print(id(3.2))
print(type("3.2"))
print(id("3.2"))
print(type('This is a string.') )
print(type("And so is this.") )
print(type("""and this.""") )
print(type('''and even this...''') )
print(type('''and even this...''') is str)
print("Bruce's beard")
print('The knights who say "Ni!"')
Strings enclosed with three occurrences of either quote symbol are called triple quoted strings.
They can contain either single or double quotes.
print('''"Oh no, Ben's bike is broken!"''')
Triple quoted strings can even span multiple lines.
print('''This message will span
several lines
of the text."""''')
For string, the surrounding quotes are not part of the value.
print('Hi')
print("Hi")
print('Hi' == "Hi")
print('Hi' is "Hi")
print(42000)
print(42,000)
print(42, 17, 56, 34, 11, 4.35, 32)
print(3.4, "hello", 45)
Exercise
1. How can you determine the type of a variable?
(A) Print out the value and determine the data type based on the value printed.
(B) Use the type function.
(C) Use it in a known equation and print the result.
(D) Look at the declaration of the variable.
2. What is the data type of ‘this is what kind of data’?
(A) Character
(B) Integer
(C) Float
(D) String
print(3.14, int(3.14))
print(3.9999, int(3.9999))
print(3.0, int(3.0))
print(-3.999, int(-3.999))
print("2345", int("2345"))
print(17, int(17))
print(int("23bottles"))
print(float("123.45"))
print(type(float("123.45")))
print(type(float("123.45")) is float)
print(type("123.45") is str)
print(str(17))
print(str(123.45))
print(type(str(123.45)))
Implicit conversion
Narrow to wide:
bool ⇒ int ⇒ float
1.0/2
Exercise
What value is printed when the following statement executes?
print( int(53.785) )
(A) Nothing is printed. It generates a runtime error.
(B) 53
(C) 54
(D) 53.785
A variable is a name that refers to a value.
Assignment statements create new variables and also give them values to refer to.
message = "What's up, Doc?"
n = 17
pi = 3.14159
The assignment statement links a name, on the left hand side of the operator(=), with a value, on the right hand side.
message = "What's up, Doc?"
n = 17
pi = 3.14159
print(message)
print(n)
print(pi)
message = "What's up, Doc?"
n = 17
pi = 3.14159
print(type(message))
print(type(n))
print(type(pi))
print(id(pi))
Variables are variable.
They can change over time
You can assign a value to a variable, and later assign a different value to the same variable.
day = "Thursday"
print(day)
day = "Friday"
print(day)
day = 21
print(day)
Variable names can be arbitrarily long.
They can contain both letters and digits, but they have to begin with a letter or an underscore.
Exercise: which variable names is illegal?
76trombones = "big parade"
more$ = 1000000
class = "Computer Science 101"
_, _class, class_, __name, __name__ = 2,3,4,5,6
76trombones = "big parade"
more$ = 1000000
class = "Computer Science 101"
- | - | - | - | - | - | - |
---|---|---|---|---|---|---|
and | as | assert | break | class | continue | def |
elif | else | except | exec | finally | for | from |
global | if | import | in | is | lambda | nonlocal |
not | or | pass | raise | return | try | while |
with | yield | True | False | None |
Programmers generally choose names for their variables that are meaningful to the human readers of the program — they help the programmer document, or remember, what the variable is used for.
Exercise
Is the following a legal variable name in Python?
A_good_grade_is_A+
(A) True
(B) False
A statement is an instruction that the Python interpreter can execute.
An expression is a combination of values, variables, operators, and calls to functions.
Expressions need to be evaluated.
print(1 + 1)
print(len("hello"))
The evaluation of an expression produces a value
y = 3.14
x = len("hello")
print(x)
print(y)
Evaluate variable y in Python shell or Notebook
>>> y = 3.14
>>> x = len("hello")
>>> print(x)
5
>>> print(y)
3.14
>>> y
3.14
y
Operators are special tokens that represent computations like addition, multiplication and division.
The values the operator works on are called operands.
Type int
Values: integers
Ops: +, –, *, /, //, %, **
Type float
Values: real numbers
Ops: +, –, *, /, **
Type bool
Values: True and False
Ops: not, and, or
Type str
+ (concatenation)
20 + 32
hour - 1
hour * 60 + minute
minute / 60
5 ** 2
(5 + 9) * (15 - 7)
print(2 + 3)
print(2 - 3)
print(2 * 3)
print(2 ** 3)
print(3 ** 2)
minutes = 645
hours = minutes / 60
print(hours)
print(7 / 4)
print(7 // 4)
minutes = 645
hours = minutes // 60
print(hours)
quotient = 7 // 3
print(quotient)
remainder = 7 % 3
print(remainder)
total_secs = 7684
hours = total_secs // 3600
secs_still_remaining = total_secs % 3600
minutes = secs_still_remaining // 60
secs_finally_remaining = secs_still_remaining % 60
print("Hrs=", hours, "mins=", minutes, "secs=", secs_finally_remaining)
Exercise
1. Evaluate the following expressions.
18 / 4
18 // 4
5 ** 2
9 * 5
5 % 2
9 % 5
6 % 6
0 % 7
Operations are performed in a set order
Parentheses make the order explicit
Python processes operators in fixed order in absence of parentheses
2*1 + 3
2*(1 + 3)
Precedence of Python Operators
**
+ –
* / // %
+ –
< > <= >=
== !=
not
and
or
print(2**1+1)
print(3*1**3)
print(2*3-1)
print(6-3+2)
print(6-(3+2))
Exercise
1. Calculate
${2^3}^2$
print(2 ** 3 ** 2)
print((2 ** 3) ** 2)
2. Evaluate the following expressions.
2*3
2 ** 3
5+2*5
(5 + 2) * 5
-4 - -4 - -4
2 ** 2 ** 0
(2 ** 2) ** 0
6/2
6/4
6.0 / 4
6 / 4.0
9.0 * 0.5
9.0 ** 0.5
6%2
7%2
6.2 % 4
3. Evaluate bool expressions.
3<5
3 < 5 and 5 < 3
True
true
True and False
True or False
not True
not not False
not False and True
not (False or True)
True and False and True
True or (False and True)
(5/0==1) and False
False and (5/0==1)
It is legal to make more than one assignment to the same variable.
A new assignment makes an existing variable refer to a new value (and stop referring to the old value).
a = 5
b = a
print(a, b)
a = 3
print(a, b)
Exercise
After the following statements, x is ___ and y is ___?
x = 15
y = x
x = 22
x = 6 # initialize x
print(x)
x = x + 1 # update x
print(x)
Python uses a built-in function to accomplish data input: input
n = input("Please enter your name: ")
print("Hello", n)
str_seconds = input("Please enter the number of seconds you wish to convert")
total_secs = int(str_seconds)
hours = total_secs // 3600
secs_still_remaining = total_secs % 3600
minutes = secs_still_remaining // 60
secs_finally_remaining = secs_still_remaining % 60
print("Hrs=", hours, "mins=", minutes, "secs=", secs_finally_remaining)
Exercise
What is printed when the following statements execute?
n = input("Please enter your age: ")
# user types in 18
print ( type(n) )
(A) <class 'str'>
(B) <class 'int'>
(C) <class 18>
(D) 18
+ : concatenation
* : repetition
print("Hello" + "World")
print("Hello"*3)
1 Alarm clock problem
You look at the clock and it is exactly 2pm. You set an alarm to go off in 51 hours. At what time does the alarm go off?
2 Alarm clock problem in general
Write a Python program to solve the general version of the above problem. Ask the user for the time now (in hours), and ask for the number of hours to wait. Your program should output what the time will be on the clock when the alarm goes off.
3 Compound interest problem
$ A = P\left( 1 + \frac{r}{n} \right)^{nt} $
where:
P is the original principal sum
r is the nominal annual interest rate
n is the compounding frequency
t is the overall length of time in years.