Professional Documents
Culture Documents
Statements
Chapter 2
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”
• Case Sensitive
http://en.wikipedia.org/wiki/Mnemonic
x1q3z9ocd = 35.0
x1q3z9afd = 12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd
print(x1q3p9afd)
hours = 35.0
What are these bits rate = 12.50
of code doing? pay = hours * rate
print(pay)
Sentences or Lines
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
0.4
The right side is an expression. Once the
expression is evaluated, the result is
placed in (assigned to) the variable on the
0.936
left side (i.e., x).
Assigning Multiple Variables in a Single Line
In Python programming, you can assign multiple variables in
one statement.
Assigning Same Value to Multiple Variables
Now let us explore another interesting feature in Python
programming. The programmer can assign the same values
to multiple variables in one statement.
Expressions…
Numeric Expressions
Operator Operation
• Because of the lack of mathematical
symbols on computer keyboards - we + Addition
use “computer-speak” to express the - Subtraction
classic math operations
* Multiplication
• Asterisk is multiplication / Division
3
Order of Evaluation
• When we string operators together - 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
<class 'str'>
>>> 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): File "<stdin>", line 1,
characters in <module>
ValueError: invalid literal for int() with base 10: 'x'
User Input
• We can instruct Python to
nam = input('Who are you? ')
pause and read data from
print('Welcome', nam)
the user using the input()
function
• Why comment?
# All done
print(bigword, bigcount)
Summary
• Type • Integer Division
• Operator precedence
Exercise
Enter Hours: 35
Enter Rate: 2.75
Pay: 96.25
Acknowledgements / Contributions