Introduction
In this lesson, you’ll work with three fundamental building blocks of Python programs: numbers, booleans, and None. You’ll perform arithmetic with integers and floats, understand how division behaves, control program logic using boolean values and comparisons, take advantage of truthy/falsy shortcuts, and use None to represent missing data safely.
1. Working with Numbers: Integers and Floats
Python has several numeric types; the two core ones you’ll use constantly are:
int: whole numbers (e.g.,0,5,-42)float: decimal numbers (e.g.,3.14,-0.5,2.0)
You’ve already assigned values to variables; now you’ll use them in arithmetic.
1.1 Declaring and Using Integer and Float Variables
# Basic numeric variables
apples = 10 # int
price_per_apple = 0.75 # float
# Arithmetic operations
total_cost = apples * price_per_apple
# Updating values
apples_bought = 3
apples = apples - apples_bought
remaining_cost = apples * price_per_apple
print("Total cost:", total_cost)
print("Remaining apples:", apples)
print("Remaining cost:", remaining_cost)
# Output
Total cost: 7.5
Remaining apples: 7
Remaining cost: 5.25
Explanation:
applesstarts as anint.price_per_appleis afloat.- Multiplying an
intby afloatproduces afloat(7.5,5.25). - You can freely mix
intandfloatin arithmetic; Python chooses the most precise type needed (here:float).
1.2 Division Behavior: / vs // vs %
Python has several division-related operators:
/→ true division (always returns afloat)//→ floor division (truncates down to the nearest whole number)%→ modulo (remainder of division)
students = 10
slices = 25
# True division (float result)
avg_slices = slices / students
# Floor division (whole slices each)
whole_slices_each = slices // students
# Remainder slices after fair share
leftover_slices = slices % students
print("Average slices per student:", avg_slices)
print("Whole slices per student:", whole_slices_each)
print("Leftover slices:", leftover_slices)
# Output
Average slices per student: 2.5
Whole slices per student: 2
Leftover slices: 5
Explanation:
/gives the precise average (2.5).//gives only the whole-number part (2).%gives the remainder (5).
// is particularly useful when you need integer results, for example for indexing or splitting data into fixed-size chunks.
2. Booleans and Comparison Operators
Booleans (bool) represent truth values: True or False. They’re essential for if statements and any logic-based decisions.
2.1 Basic Booleans and Comparisons
Comparison operators create boolean values:
==,!=→ equal, not equal<,>,<=,>=→ ordering comparisons
age = 20
is_adult = age >= 18
has_ticket = True
can_enter = is_adult and has_ticket
print("Is adult?", is_adult)
print("Has ticket?", has_ticket)
print("Can enter?", can_enter)
# Output
Is adult? True
Has ticket? True
Can enter? True
Explanation:
age >= 18evaluates toTrue, stored inis_adult.has_ticketis a boolean literal.andcombines them: both must beTrueforcan_enterto beTrue.
2.2 Using Booleans in Program Logic
score = 73
passed_exam = score >= 50
if passed_exam:
print("You passed the exam!")
else:
print("You did not pass. Try again.")
# Output
You passed the exam!
Explanation:
- The comparison calculates
passed_examonce. - The
ifuses the boolean directly for clearer, reusable logic.
3. Truthy and Falsy Values in Conditionals
In Python, many non-boolean values can be used directly in conditions. Python interprets them as truthy or falsy.
Common falsy values:
0,0.0""(empty string)[],{},set()(empty containers)None
Almost everything else is truthy.
3.1 Concise Checks with Truthy/Falsy
Instead of writing explicit comparisons like if len(name) > 0:, you can use the value directly:
username = input("Enter username (leave blank for guest): ")
if username:
print("Welcome,", username)
else:
print("Welcome, guest user")
# Possible Output (if user enters Alice)
Enter username (leave blank for guest): Alice
Welcome, Alice
# Possible Output (if user just presses Enter)
Enter username (leave blank for guest):
Welcome, guest user
Explanation:
- An empty string is falsy, so
if username:fails when the user presses Enter. - Any non-empty string is truthy, so the
ifbranch runs when a name is given.
3.2 Using Numbers as Conditions
items_in_cart = 0
if items_in_cart:
print("You have items in your cart.")
else:
print("Your cart is empty.")
# Output
Your cart is empty.
Explanation:
0is falsy, so theelsebranch executes.- If
items_in_cartwere3, theifbranch would run.
4. Using None for Missing or Unknown Data
None is a special singleton object used to represent “no value”, “unknown”, or “not yet set”.
4.1 Declaring and Checking for None
# User hasn't set their nickname yet
nickname = None
if nickname is None:
print("No nickname set. Using full name instead.")
else:
print("Nickname:", nickname)
# Output
No nickname set. Using full name instead.
Explanation:
nicknameholdsNoneto signal “missing value”.- You must compare to
Noneusingisoris not, not==.
4.2 Why Use is with None?
None is a single shared object in a Python process. The is operator checks identity (same object in memory). This is the recommended, reliable way to test for None:
result = None
# Simulating an operation that might fail
user_input = "42"
if user_input.isdigit():
result = int(user_input)
if result is None:
print("Conversion failed.")
else:
print("Converted number:", result)
# Output
Converted number: 42
Explanation:
resultstarts asNone(no value yet).- If conversion succeeds,
resultbecomes anint. - Checking
result is Nonetells you whether the operation produced a value.
4.3 Combining None with Truthiness
Remember: None is falsy, so you can use it directly in conditions, but still use is when you specifically care about missing-vs-zero or missing-vs-empty:
discount = None # could also be 0 or a positive number later
if discount is None:
print("No discount information available.")
elif discount == 0:
print("No discount applied.")
else:
print("Discount applied:", discount, "%")
# Output
No discount information available.
Explanation:
Nonemeans “we don’t know yet if there is a discount”.0means “we explicitly know there is no discount”.- Positive values represent an actual discount.
Summary / Key Takeaways
In this lesson on Numbers, Booleans, and None, you have learned:
- Numeric Types and Arithmetic: How to declare and use
intandfloatvariables in arithmetic expressions, including mixing them in calculations. - Division Operators: The difference between
/(true division),//(floor division), and%(modulo) and when each is appropriate. - Booleans for Logic Control: How comparison operators create boolean values and how to use them with logical operators (
and,or,not) to control program flow. - Booleans in Conditionals: How to store comparison results in boolean variables and reuse them in
if/elsestructures for clearer, more maintainable code. - Truthy and Falsy Values: How non-boolean values like empty strings, zero, and empty collections behave in conditions and how to leverage this for concise checks.
- Using
Nonefor Missing Data: HowNonerepresents the absence of a value and is commonly used for optional or not-yet-computed results. - Safe Comparison with
None: Why you should always useisoris notwhen checking forNone, instead of==, to avoid subtle bugs. - Distinguishing Missing vs. Valid Zero Values: How to design logic that clearly separates
None(unknown/missing) from0or empty values that are valid but carry specific meaning.
