Download Introduction to Python and programming and more Slides Advanced Computer Programming in PDF only on Docsity!
Introduction to Python
and programming
Ruth Anderson UW CSE 160 Autumn 2021
- Python is a calculator 2. A variable is a container
- Different types cannot be compared 4. A program is a recipe
1. Python is a calculator
You type expressions.
Python computes their values.
- If precedence is unclear, use parentheses
- (72 – 32) / 9 * 5 Try typing some of these expressions into a python interpreter
Another evaluation example
2. A variable is a container
Changing existing variables
(“re-binding” or “re-assigning”)
x = 2 x y = y x = 5 x y
- “=” in an assignment is not a promise of eternal equality
- This is different than the mathematical meaning of “=”
- Evaluating an expression gives a new (copy of a) number, rather than changing an existing one 2 An expression that can be typed into a python interpreter to be evaluated. Not a statement to put into a python program. Nothing printed from an assignment statement Try typing into a python interpreter
How an assignment is executed
- Evaluate the right-hand side to a value
- Store that value in the variable x = 2 print(x) y = x print(y) z = x + 1 print(z) x = 5 print(x) print(y) print(z) State of the computer: Printed output: To visualize a program’s execution: http://pythontutor.com A custom link to this program is here This is a python program that could be typed into a text editor.
Boolean Expressions
(value is True or False )
22 > 4 22 < 4 22 == 4 x = 100 # Assignment, not conditional! 22 = 4 # Error! x >= 5 x >= 100 x >= 200 not True not (x >= 200) 3 < 4 and 5 < 6 4 < 3 or 5 < 6 temp = 72 water_is_liquid = temp > 32 and temp < 212 Order of Precedence: Numeric operators: +, *, ** Mixed operators: <, >=, == Boolean operators: not, and, or 13 Also: see a program printing these expressions in python tutor Try typing these expressions into a python interpreter
What do you think?
What is printed out by the following Python code:
- print(2 < 7 or 3 > 12)
- print(not ((2 < 3) and (4 > 100)))
temp = 72 is_liquid = temp > 32 and temp < 212 print(is_liquid) temp = 300 print(is_liquid) See this program in python tutor
3. Different types cannot be compared
Types of values
- Integers (int): -22, 0 , 44
- Real numbers (float): 2.718, 3.
- float, for “floating point”
- Arithmetic is approximate
- Strings (str): "I love Python", ""
- Truth values (bool): True, False
Operations behave differently
on different types
15.0 / 4. 15 / 4 # Would have been truncated in Python 2. 15.0 / 4 15 / 4. Type conversion: float(15) int(15.0) int(15.5) int("15") str(15.5) float(15) / 4 See a program printing these expressions in python tutor Try typing these expressions into a python interpreter
4. A program is a recipe