Professional Documents
Culture Documents
Intro To CS Lec03
Intro To CS Lec03
Variables
A variable is a name that refers to a
value which is used to refer to the value
later
x=3
message = ‘hello’
Variables
variables
Variables
You can change the contents of a variable in a later
statement
>>> PI = 3.14
Literals
Literal/unnamed constant/magic number:
not given a name, the value that you see is
literally the value that you have.
17
x
x +17
Sentences or Lines
x=5 x 5
x=x+1 x 6
Basic Form
<variable> = <expr>
Assignment Statements
We assign a value to a variable using the
assignment statement (=)
An assignment statement consists of an expression
on the right hand side and a variable to store the
result
x = 3.9 * x * ( 1 - x )
A variable is a memory location x 0.6
used to store a value (0.6).
0.6 0.6
x = 3.9 * x * ( 1 - x )
0.4
x = 3.9 * x * ( 1 - x )
to do first
x = 1 + 2 * 3 - 4 / 5 ** 6
Operator Precedence Rules
Highest precedence rule to lowest precedence rule
Parenthesis
Power 1 + 10
Multiplication
Addition
Left to Right
11
1 + 2 ** 3 / 4 * 5
>>> x = 1 + 2 ** 3 / 4 * 5
>>> print(x) 1+8/4*5
11
>>> Note 8/4 goes before 4*5 1+2*5
because of the left-right
rule.
Parenthesis 1 + 10
Power
Multiplication
Addition 11
Left to Right
Operator Precedence
When writing code - use parenthesis
Parenthesis
When writing code - keep mathematical Power
Multiplication
expressions simple enough that they are Addition
Left to Right
easy to understand
Complex numbers
Long integers
Doubles
String
String is a sequence of characters.
‘hello’
‘a’
‘1’
‘1 + 3’
“’”
Boolean (bool)
True (1)
False (0)
Types in Python
In Python variables, literals, and
>>> ddd = 1 + 4
constants have a “type”
>>> print(ddd)
Python knows the difference between 5
>>> eee = 'hello ' + 'there'
an integer number and a string
>>> print(eee)
For example “+” means “addition” if hello there
something is a number and
“concatenate” if something is a string
Several Types of Numbers
Numbers have two main types
hours = 35.0
rate = 12.50
What is this
pay = hours * rate
code doing?
print pay