Decisions I
CDS1010: Week 1A
Wiedemann • Fall 2025
Formatted Strings (f-strings)
- f-string: String prefixed with
f that replaces expressions inside braces {} with their values.
- Simplifies mixing text and variables without concatenation.
name = "Alex"
print(f"Hello, {name}!")
Floating-Point Numbers
- float: Numbers with a fractional part; e.g.
3.14, 2.0.
- Division (
/) of two ints produces a float.
type(value) returns a variable's data type.
- Format
floats in f-strings using e.g. {value:.2f}
x = 8
y = 3
z = x / y
print(z) # 2.6666666666666665
print(type(z)) # <class 'float'>
print(f"{z:.2f}") # 2.67
Rounding & Truncating Floats
round(value, 2) returns a float rounded to two decimal places.
int(value) returns an int after truncating the fractional part.
z = 2.6666666666666665
print(round(z, 2)) # 2.67
print(int(z)) # 2
Booleans
- Boolean (
bool): Data type that can be only one of two values: True or False.
- Comparison operators
==, !=, <, <=, >, >= return bool values.
print(3 < 5) # True
print(2 == 3) # False
Floating-Point Surprises
- Some
floats cannot be represented exactly in memory, leading to tiny tiny errors.
Consequently, directly comparing floats with == may fail.
- Use
math.isclose() for safer comparisons.
import math
total = 0.1 + 0.1 + 0.1
print(total == 0.3) # False
print(math.isclose(total, 0.3)) # True
The decimal module can provide exact decimal arithmetic, but this is rarely needed.
Conditional Logic
if executes a block (or suite) of code when its condition is True.
else handles the complementary case.
- The entire block of code following
if or else must be indented by 4 spaces.
if condition:
# code to execute if condition is True (nothing happens if False)
if condition:
# code to execute if condition is True
else:
# code to execute if condition is False