Pythonlearn 02 Expressions
Pythonlearn 02 Expressions
Constants
Variables, Expressions, and • Fixed values such as numbers, letters, and strings, are called
Statements “constants” because their value does not change
• Numeric constants are as you expect
Chapter 2 >>> print(123)
• String constants use single quotes (') 123
or double quotes (") >>> print(98.6)
98.6
Python for Everybody >>> print('Hello world')
www.py4e.com Hello world
1 2
3 4
1
10/01/21
5 6
7 8
2
10/01/21
hours = 35.0
What are these bits What are these bits rate = 12.50
of code doing? of code doing? pay = hours * rate
print(pay)
9 10
11 12
3
10/01/21
0.4 0.4
The right side is an expression. Once the
The right side is an expression. expression is evaluated, the result is
0.936 placed in (assigned to) the variable on the
0.936
Once the expression is evaluated, the
result is placed in (assigned to) x. left side (i.e., x).
13 14
Numeric Expressions
Operator Operation
• Because of the lack of mathematical
symbols on computer keyboards - we + Addition
Expressions… use “computer-speak” to express the - Subtraction
classic math operations
* Multiplication
• Asterisk is multiplication / Division
15 16
4
10/01/21
17 18
>>> print(x)
Highest precedence rule to lowest precedence rule: 1 + 8 / 4 * 5
11.0
• Parentheses are always respected Parenthesis >>>
Power 1 + 2 * 5
• Exponentiation (raise to a power) Multiplication Parenthesis
Addition Power
• Multiplication, Division, and Remainder
Left to Right Multiplication 1 + 10
• Addition and Subtraction Addition
Left to Right
• Left to right 11
19 20
5
10/01/21
21 22
23 24
6
10/01/21
25 26
String
>>> sval = '123'
>>> type(sval)
<class 'str'>
User Input
Conversions
>>> print(sval + 1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object • We can instruct Python to
nam = input('Who are you? ')
• You can also use int() and to str implicitly
>>> ival = int(sval)
pause and read data from
the user using the input()
print('Welcome', nam)
float() to convert between >>> type(ival)
27 28
7
10/01/21
29 30
31 32
8
10/01/21
Pay: 96.25
33 34