1 of 10

CS 149

Professor: Alvin Chao

Lecture 4 - Order of Operations

2 of 10

Order of Operations

  • The Python language defines a specific order of execution for math and other operations. For example, multiplication and division take precedence over addition and subtraction. Using parentheses, you can override the order of operations. The following table lists some Python operators from highest precedence to lowest precedence. PEUMA

()

Parenthesis

**

Exponentiation

+, -

Unary(Positive, negative)

*, /, //, %

Multiplication, division, floor division, modulus(remainder)

+, -

Addition and subtraction

3 of 10

Memory diagrams

  • Draw a memory diagram for the following code.

width = 10 �score = 89.5 �first = "John"

other = "Smith" �width = 20�score = 0.94 �first = "Taylor" �score = width �other = first

  • What is the output of the following statements after running the code above? Explain your answer using the diagram.
  • first = "Smith" �print(other)

4 of 10

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)

5 of 10

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

6 of 10

String indexing

[ 0 ] [ 1 ] [ 2 ] [ 3 ]

“W O R D “

word = “WORD”

print(word[-2])

7 of 10

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 zeroesnumber = 4

print(f'{number:03d}')

>>>004

Alignment

print(f'{"apple" : >30}')

print(f'{"apple" : <30}')

print(f'{"apple" : ^30}')

8 of 10

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}')

9 of 10

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

10 of 10

  • Acknowledgements
  • Parts of this activity are based on materials developed by Helen Hu and Urik Halliday, modified by Chris Mayfield and Nathan Sprague, and licensed under CC BY-NC 4.0 International

</end>