CS 149
Professor: Alvin Chao
Lecture 4 - Order of Operations
Order of Operations
() | Parenthesis |
** | Exponentiation |
+, - | Unary(Positive, negative) |
*, /, //, % | Multiplication, division, floor division, modulus(remainder) |
+, - | Addition and subtraction |
Memory diagrams
width = 10 �score = 89.5 �first = "John"
other = "Smith" �width = 20�score = 0.94 �first = "Taylor" �score = width �other = first
Math module
https://docs.python.org/3/library/math.html
Need to have import math at the top of your program.
import math
math.e ** x or pow(math.e, x)
Trigonometric functions
Python and other languages do angles in radians by default for sin, cos, tan.
import math�print (math.degrees(90))
print(math.radians(90))
x = math.cos(1)
y = x * 180/math.pi�print(y)�30.957
String indexing
[ 0 ] [ 1 ] [ 2 ] [ 3 ]
“W O R D “
word = “WORD”
print(word[-2])
String Formatting
See section 3.9 Table 3.9.2
Round to a decimal place
number = 5.75253545
print(f'{number:.2f}')
>>>5.75
Leading zeroes�number = 4
print(f'{number:03d}')
>>>004
Alignment
print(f'{"apple" : >30}')
print(f'{"apple" : <30}')
print(f'{"apple" : ^30}')
Type Conversion and String formatting
number = 6.5
price_per_item = 2.75
amount = int(number) * price_per_item
print(f'{int(number)} items cost ${amount}')
More String Formatting
Currency
large_number = 126783.6457
print(f'Currency format for large_number with two decimal places: ${large_number:.2f}')
# Returns
# Currency format for large_number with two decimal places: $126783.65
Comma Separators
large_number = 126783.6457
print(f'Currency format for large_number with two decimal places and comma seperators: ${large_number:,.2f}')
# Returns
# Currency format for large_number with two decimal places and comma seperators: $126,783.65
</end>