Variables, Expressions, Statements
Variables, Expressions, Statements
statements
Chapter 2
Constants
x = 12.2 x 12.2
y = 14
y 14
Variables
• A variable is a named place in the memory where a programmer can store
data and later retrieve the data using the variable “name”
hours = 35.0
What are these bits rate = 12.50
of code doing? pay = hours * rate
print(pay)
Assignment Statements
• We assign a value to a variable using the assignment statement (=)
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
3
Order of Evaluation
• When we write operators without parentheses - Python must know
which one to do first
x = 1 + 2 * 3 - 4 / 5 ** 6
Operator Precedence Rules
Highest precedence rule to lowest precedence rule:
• Left to right
1 + 2 ** 3 / 4 * 5
>>> x = 1 + 2 ** 3 / 4 * 5
>>> print(x)
11.0 1 + 8 / 4 * 5
>>>
1 + 2 * 5
Parenthesis
Power
Multiplication 1 + 10
Addition
Left to Right
11
Operator Precedence Parenthesis
Power
• Remember the rules top to bottom Multiplication
Addition
• When writing code - use parentheses Left to Right
Conversions
>>> print(sval + 1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object
•
to str implicitly
You can also use int() and >>> ival = int(sval)
float() to convert between >>> type(ival)
<class 'int'>
strings and integers >>> print(ival + 1)
124
• You will get an error if the string >>> nsv = 'hello bob'
>>> niv = int(nsv)
does not contain numeric Traceback (most recent call last):
characters File "<stdin>", line 1, in <module>
ValueError: invalid literal for int()
with base 10: 'x'
User Input
• We can instruct Python to
name = input('Who are you?\n')
pause and read data from
print('Welcome', name)
the user using the input()
function
•
ValueError Traceback (most recent
If the user enters something call last)
different than a string of <ipython-input-4-155078aed62b> in
<module>()
digits, you get an error ----> 1 int(inp)
ValueError: invalid literal for
int() with base 10: 'What?'
Comments in Python
• Why comment?
• Operator precedence
Exercises
Pay: 61.75
Exercises
width//2
width/2.0
height/3
Exercises