Lecture 5
Lecture 5
ing
Lecture 5
OUTLINE
Objects: Values and types
Tuples
Variables
Operators and operands
Expressions and Statements
Case study: Photo Processing
OBJECTS: VALUES AND TYPES
Booleans(truth values)
True or False
Complex objects
Tuples
(1, 3, 5, 7, 9)
(“red”, “green”, “blue”)
(777, “a lucky number”)
Type inquires
>>>type(3) >>>type(3 + 5j)
<Type ‘int’> <Type ‘complex’>
>>>type(3.145) >>>type(True)
<Type ‘float’> <Type ‘bool’>
>>>type(“Welcome”)
<Type ‘str’>
>>> from cs1robots import *
>>> type(Robot())
<class ’cs1robots.Robot’>
message = “Welcome“
n = 17
from cs1robots import *
create_world()
hubo = Robot()
pi = 3.1415926535897931
finished = True
Good:
msg = “cce20003 is fantastic“
ba13 = 13.0
Bad:
more@ = "illegal character“
13a = 13.0
def = “Definition”
The same name can be assigned to different objects (of
different types) in a program, e.g.,
n = 17 17
n = "Seventeen“ n “Seventeen”
n = 17.0 17.0
>>> b = "banana"
>>> print b.upper()
BANANA
>>>from cs1robots import *
>>> hubo = Robot()
>>> hubo.move()
>>> hubo.turn_left()
>>>from cs1media import *
>>>img = load_picture(“photos/yuna1”)
>>> print img.size()
(58, 50)
>>> img.show()
hubo = Robot("yellow”)
hubo.move() The same object may have
ami = hubo more than one name!
hubo = Robot("blue")
hubo.move()
ami.turn_left() hub yellow ro-
ami.move() bot
o
ami
blue ro-
bot
OPERATORS AND OPERANDS
Arithmetic operators are special symbols that repre-
sent computations such as +, -, *, /, %, and **. Oper-
ands are the values to which an operator is applied.
>>> 2 ** 16 a ** b = ab
65536
>>>15.3 + 3.0
18.3
>>>7 % 5
2
>>>7 / 5
1
>>>7.0 / 5
1.4
EXPRESSIONS AND STATEMENTS
Expressions
Anexpressionisacombinationofobjects,variables,operator
s,andfunctioncalls:
3.0*(2**15-12/4)+4**3
Theoperatorshaveprecedenceasinmathematics:
1. exponentiation**
2. multiplicationanddivision* ,/,%
3. additionandsubtraction+,-
Whenindoubt,useparentheses!
How to represent? Which ones are right?
a/2*pi a/(2*pi ) a/2/pi
The operators + and * can be used for strings:
Repeating 8 times!
Relational operators ==, !=, >, <, <=, and >= are
used to compare objects. The results are Boolean values, True
or False. A Boolean expression is an expression whose
value is of type bool. They are used in if and while
statements.
>>>27 == 14
False
>>> 3.14 != 3.14
False
if x % 2 != 0:
print “x is odd”
The keywords not, and, and or are logical operators:
block of statements
For i in range(7):
What does this short
print "*“ * i code do ?
*
**
***
****
*****
******
CASE STUDY: PHOTO PROCESSING
…… ……
0,1 1,1 2,1 w-1,1
…… …… …… …… …… ……
…… …… …… …… …… ……
img = load_picture(“./images/yuna.jpg")
w, h = img.size()
for y in range(h):
for x in range(w):
r, g, b = img.get(x, y)