Numeric Expressions
- Becuase of the lack of mathematical symbols on computer keyboards - we use “computer-speak” to express the classic math operations
- Asterisk is multiplication
- Exponentiation (raise to a power) looks different than in math
Operator | Operation |
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
** | Power |
% | Remainder |
Order of Evaluation
- When we string operators together - Python must know which one to do first
- This is called operator precedence
- Which operator takes precedence over the others?
Parenthesis → Power → Multiplication → Addition → Left to Right
Operator Precedence
- Remember the rules top to bottom
- When writing code - use parentheses
- When writing code - keep mathematical expressions simple enough that they are easy to understand
- Break long series of mathematical operations up to make them more clear
What does “Type” Mean?
- In Python variables, literals, and constants have a “type”
- Python knows the difference between an integer number and a string
- For example “+” means “addition” if something is a number and “concatenate” if something is a string
>>> ddd = 1 + 4
>>> print(ddd)
5
>>> eee = 'hello ' + 'there'
>>> print(eee)
hello there
Type Matters
- Python knows that “type” everything is
- Some operations are prohibited
- You cannot “add 1” to a string
- We can ask Python what type something is by using the type() function
Type Conversions
- When you put an integer and floating point in an expression, the integer is implicitly converted to a float
- You can control this with the built-in functions int() and float()
>>> print(float(99) + 100)
199.0
>>> i = 42
>>> type(i)
<class 'int'>
>>> f = float(i)
>>> print(f)
42.0
>>> type(f)
<class 'float'>
Integer Division
Integer division produces a floating point result
>>> print(10/2)
5.0
>>> print(9/2)
4.5
String conversions
- You can also use int() and float() to convert between strings and integers
- You will get an error if the string does not contain numeric characters
- We can instruct Python to pause and read data from the user using the input() function
- The input() function returns a string
nam = input('Who are you? ')
print('Welcome', nam)
- If we want to read a number from the user, we must convert it from a string to a number using a type conversiong function
- Later we will deal with bad input data
inp = input('Europe floor?')
usf = int(inp) + 1
print('US floor', usf)
- Anything after a # is ignored by Python
- Why comment?
- Describe what is going to happen in a sequence of code
- Document who wrote the code or other ancillary information
- Turn off a ling of code - perhaps temporarily