CMPSC 100 Computational Expression
Building upon Python fundamentals
Examples:
Python’s built-in data types:
int
: Whole numbers (e.g., 42, -17)float
: Decimal numbers (e.g., 3.14, -2.5)str
: Text/strings (e.g., “Hello”, ‘Python’)bool
: True or Falselist
: Ordered collection (e.g., [1, 2, 3])dict
: Key-value pairs (e.g., {“name”: “Alice”})Use the type()
function to check a variable’s type:
Working with numbers in Python
Python supports standard mathematical operations:
+
Addition-
Subtraction*
Multiplication/
Division (returns float)//
Floor division (returns int)%
Modulus (remainder)**
Exponentiation (power)Python follows standard mathematical precedence (PEMDAS):
()
**
*
and Division /
, //
+
and Subtraction -
Use the round()
function to round decimal numbers:
# Basic rounding
temperature = 22.666666
print(round(temperature)) # 23 (no decimal places)
print(round(temperature, 1)) # 22.7 (1 decimal place)
print(round(temperature, 2)) # 22.67 (2 decimal places)
# Useful for displaying sensor data
percentage = 66.66666
print("Battery: " + str(round(percentage, 1)) + "%") # Battery: 66.7%
Efficient ways to update variables
Shorthand for common operations:
+=
Add and assign-=
Subtract and assign*=
Multiply and assign/=
Divide and assign//=
Floor divide and assign%=
Modulus and assign**=
Exponent and assignWorking with text data
Use +
to join strings together:
Use *
to repeat strings:
Extract parts of strings using square brackets:
Common string methods for text processing:
text = "Hello World"
name = "alice"
# Convert to uppercase
print(text.upper()) # "HELLO WORLD"
print(name.upper()) # "ALICE"
# Convert to lowercase
print(text.lower()) # "hello world"
# Other useful methods
print(text.replace("World", "Python")) # "Hello Python"
print(len(text)) # 11 (length of string)
Interacting with users
Use input()
to get text from the user:
Different ways to format output:
Converting between data types
Type conversion (casting) changes a value from one data type to another:
Common conversion functions:
int()
- Convert to integerfloat()
- Convert to floating-point numberstr()
- Convert to stringbool()
- Convert to boolean# From numbers (0 is False, everything else is True)
print(bool(0)) # False
print(bool(1)) # True
print(bool(-5)) # True
print(bool(0.0)) # False
print(bool(3.14)) # True
# From strings (empty string is False)
print(bool("")) # False
print(bool("Hello")) # True
print(bool("0")) # True (string "0", not number 0)
Python automatically converts types in some situations:
Be careful with invalid conversions:
Understanding how operators work with different data types
The same operator can behave differently with different data types:
# * with two integers
result = 3 * 4 # 12 (multiplication)
# * with integer and float
result = 3 * 4.0 # 12.0 (multiplication, result is float)
# * with integer and string
result = "Hey" * 3 # "HeyHeyHey" (string repetition)
# + with numbers vs strings
result = 3 + 4 # 7 (arithmetic addition)
result = "3" + "4" # "34" (string concatenation)
Type awareness helps you predict behavior:
# These work as expected
print(5 + 3) # 8 (arithmetic)
print("Hello" + " World") # "Hello World" (concatenation)
# These cause errors - mixed types!
# print("5" + 3) # TypeError!
# print(5 + "3") # TypeError!
# Solution: Convert types explicitly
print("5" + str(3)) # "53" (both strings)
print(int("5") + 3) # 8 (both numbers)
Avoiding pitfalls
❌ Common errors:
✅ Correct approaches:
# Integer division vs. regular division
print(7 / 2) # 3.5 (regular division)
print(7 // 2) # 3 (floor division)
# Division by zero causes errors
# print(5 / 0) # ZeroDivisionError!
# Always be careful with division
numerator = 10
denominator = 0
print(f"Attempting to divide {numerator} by {denominator}")
# We'll learn how to handle this safely with conditional statements