# CMU 15-110: Principles of Computing Data and Expressions

1. Some Builtin Types
print("Some basic types in Python:") print(type(2)) # int print(type(2.2)) # float print(type('ABC')) # str (string) print(type(True)) # bool (boolean)

2. Some Builtin Constants
print("Some constants we will use:") print(True) print(False) print(None) import math print(math.pi)

3. Some Builtin Functions
print("Type conversion functions:") print(int(2.8)) # convert to an integer (int) print(float('42')) # convert to a floating point number print("And some basic math functions:") print(abs(-5)) # absolute value print(max(2,3)) # return the max value print(min(2,3)) # return the min value print(pow(2,3)) # raise to the given power (pow(x,y) == x**y) print(round(2.354, 1)) # round with the given number of digits

4. Some Builtin Operators
 Category Operators Arithmetic +, -, *, /, //, **, % Relational <, <=, >=, >, ==, != Assignment +=, -=, *=, /= Logical and, or, not

5. Types Affect Semantics
print(3 * 2) print(3 * "abc") print(3 + 2) print("abc" + "def") print(3 + "def")

6. Integer Division
print(5/2) # 2.5 print(5//2) # 2

7. The Remainder Operator (%)
print(" 6%3 =", ( 6%3)) print(" 5%3 =", ( 5%3)) print(" 1%3 =", ( 1%3))

8. Operator Order
print(2+3*4) # prints 14, not 20

9. Approximate Values of Floating-Point Numbers
print(0.1 + 0.1 == 0.2) # True, but... print(0.1 + 0.1 + 0.1 == 0.3) # False! print(0.1 + 0.1 + 0.1) # prints 0.30000000000000004 (uh oh) print((0.1 + 0.1 + 0.1) - 0.3) # prints 5.55111512313e-17 (tiny, but non-zero!)

Equality Testing with almostEqual:
print("The problem....") d1 = 0.1 + 0.1 + 0.1 d2 = 0.3 print(d1 == d2) # False (never use == with floats!) print() print("The solution...") epsilon = 10**-10 print(abs(d2 - d1) < epsilon) # True! print() print("Once again, using a useful helper function, almostEqual:") def almostEqual(d1, d2): epsilon = 10**-10 return (abs(d2 - d1) < epsilon) d1 = 0.1 + 0.1 + 0.1 d2 = 0.3 print(d1 == d2) # still False, of course print(almostEqual(d1, d2)) # True, and now packaged in a handy reusable function!

10. Short-Circuit Evaluation
def yes(): return True def no(): return False def crash(): return 1/0 # crashes! print(no() and crash()) # Works! print(crash() and no()) # Crashes! print (yes() and crash()) # Never runs (due to previous crash), but would also crash (without short-circuiting)

Once again, using the "or" operator:
def yes(): return True def no(): return False def crash(): return 1/0 # crashes! print(yes() or crash()) # Works! print(crash() or yes()) # Crashes! print(no() or crash()) # Never runs (due to crash), but would also crash (without short-circuiting)