Variables, Types & Operators
After this lesson, you will be able to:
- Create variables and assign values to them using the = operator
- Identify and use the five core Python types: int, float, str, bool, and None
- Convert between types using int(), float(), str(), and bool()
- Format strings with f-strings for clean, readable output
- Read user input with the input() function and convert it to the right type
- Distinguish is from == for identity vs equality checks, and understand why small numbers behave differently than large ones in comparisons
Before You Start
#Variables — Labeled Boxes for Data
=:age = 16
name = "Alex"
is_student = True
gpa = 3.85That is it. No special keywords, no type declarations. Python figures out the type automatically.
Try it! Open the Python REPL (bottom-right of the screen: click Quick Actions, then Python) and type these lines yourself. Change the values and see what happens.
#Naming Rules
Python has strict rules about variable names:
# VALID names
student_name = "Alex" # snake_case (Python convention)
age2 = 17 # can contain numbers (but not start with one)
_private = "secret" # can start with underscore
MAX_RETRIES = 3 # ALL_CAPS for constants (by convention)# INVALID names -- these cause errors
2cool = "nope" # ERROR: cannot start with a number
my-name = "nope" # ERROR: hyphens are not allowed (use underscores)
class = "nope" # ERROR: 'class' is a reserved keyword
my name = "nope" # ERROR: spaces are not allowed
snake_case for variable names (lowercase words separated by underscores). This is different from JavaScript's camelCase. Every Python developer follows this convention.#Reassignment
Variables can be reassigned at any time:
score = 0
print(score) # 0
score = 100
print(score) # 100
score = score + 50 # use the old value to compute the new value
print(score) # 150
score += 25 # shorthand for score = score + 25
print(score) # 175+= shorthand works for all arithmetic operators: -=, *=, /=, //=, **=, %=.After running `x = 5; y = x; x = 10`, what is the value of y?
#The Five Core Types
1. int — Integers (Whole Numbers)
age = 16
population = 8_000_000_000 # underscores for readability
negative = -42
zero = 0
print(type(age)) # <class 'int'>huge = 2 ** 1000 # a number with 302 digits. Python handles it.
print(huge)2. float — Floating-Point Numbers (Decimals)
pi = 3.14159
temperature = -40.0
price = 19.99 # money needs decimals
tiny = 1e-8 # scientific notation: 0.00000001
print(type(pi)) # <class 'float'>print(0.1 + 0.2) # 0.30000000000000004 (not exactly 0.3!)This happens because computers store decimals in binary, and some decimal fractions cannot be represented exactly. It rarely matters in practice, but it is good to know.
3. str — Strings (Text)
name = "Alex"
prompt = 'What is the meaning of life?'
multiline = """This is a string
that spans multiple
lines."""
empty = "" # empty string -- still a string, just with no characters
print(type(name)) # <class 'str'>
print(len(name)) # 4New word alert: ImmutableMutabilityWhether an object can be changed in place. Lists, dictionaries and sets can be; numbers, strings and tuples cannot — changing one of those always makes a new object and leaves the old one alone.Learn more → means "cannot be changed." Think of a printed book — you can read it but can't edit the pages. Strings and numbers are immutable in Python.
4. bool — Booleans (True/False)
is_raining = True
has_gpu = False
print(type(is_raining)) # <class 'bool'>
# Booleans come from comparisons
print(10 > 5) # True
print(10 == 5) # False
print(10 != 5) # True
print(10 >= 10) # Trueif statement, every while loop, every filter — they all depend on booleans.5. None — The Absence of a Value
result = None
print(type(result)) # <class 'NoneType'>
print(result) # NoneNone is not zero, not an empty string, not False. It means "no value at all." It is Python's way of saying "nothing here yet." You will see it when a function does not explicitly return anything.What is type(3.14)?
#Type Conversion
Sometimes you need to convert between types. Python gives you built-in functions for this:
# String to int
age_str = "16"
age_num = int(age_str)
print(age_num + 1) # 17 (math works now)
# String to float
price_str = "9.99"
price = float(price_str)
print(price * 2) # 19.98
# Number to string
score = 100
message = "Your score: " + str(score)
print(message) # Your score: 100
# Float to int (truncates -- does not round!)
pi = 3.99
print(int(pi)) # 3 (not 4!)
# Everything to bool
print(bool(0)) # False
print(bool(42)) # True (any non-zero number is True)
print(bool("")) # False (empty string is False)
print(bool("hello")) # True (any non-empty string is True)
print(bool(None)) # FalseTrue or False) are important. In Python, these values are "falsy" (treated as False): 0, 0.0, "", None, [], {}, set(). Everything else is "truthy."What happens when you run int("3.14")?
int() refuses to silently discard data. Strings like "3.14" contain a decimal point, and int() only parses clean integers like "42". To convert a decimal string to an int, you need two steps: int(float("3.14")) → 3. This protects you from silent data loss — Python errors loudly instead of giving you a wrong answer.#Why Type Conversion Matters
Anything a user types arrives as text, so converting is a daily job:
# A user enters a number, but it arrives as text
user_input = "19.99" # this is a string from a web form
price = float(user_input) # convert to a number before doing maths
# A score becomes a decision
score = 0.87
verdict = "pass" if score > 0.5 else "fail" # float to decision
# Brightness is stored 0-255, but you want it as 0.0-1.0
brightness = 200
normalized = brightness / 255.0 # now it is 0.784...What happens when you run `int("3.14")`?
Hit aTypeErrororValueError? Conversion mistakes (int("abc"),"3" + 1) are the #1 source of these in your first month. See the error decoder for plain-English fixes.
#F-Strings — The Best Way to Format Text
f before the opening quote, and put variables inside curly braces {}:name = "Alex"
age = 16
gpa = 3.856
# f-strings -- clean and readable
print(f"My name is {name} and I am {age} years old.")
# Output: My name is Alex and I am 16 years old.
# You can put any expression inside the braces
print(f"Next year I will be {age + 1}.")
# Output: Next year I will be 17.
# Format numbers with precision
print(f"My GPA is {gpa:.2f}")
# Output: My GPA is 3.86 (rounded to 2 decimal places)
# Format large numbers with commas
books = 175_000
print(f"The library has {books:,} books")
# Output: The library has 175,000 books
# Format as percentage
accuracy = 0.9234
print(f"Model accuracy: {accuracy:.1%}")
# Output: Model accuracy: 92.3%% formatting and .format() method. Always use f-strings — they are cleaner and faster.#Getting User Input
input() function pauses your program and waits for the user to type something:This code calls input(). Python here can't pause to ask you, so type the answers below before running — one value per line, in the order the program asks for them.
name = input("What is your name? ")
print(f"Hello, {name}! Welcome to Python.")
# IMPORTANT: input() always returns a string!
age_str = input("How old are you? ")
age = int(age_str) # convert to int for math
print(f"In 10 years you will be {age + 10}.")
# Common pattern: convert inline
temperature = float(input("Enter temperature in Fahrenheit: "))
celsius = (temperature - 32) * 5 / 9
print(f"{temperature}F = {celsius:.1f}C")input() always returns a string, even if the user types a number. You must convert it with int() or float() if you want to do math.#Operators Beyond Arithmetic
Python has comparison and logical operators that produce boolean values:
#Comparison Operators
x = 10
print(x == 10) # True (equal to)
print(x != 5) # True (not equal to)
print(x > 5) # True (greater than)
print(x < 5) # False (less than)
print(x >= 10) # True (greater than or equal to)
print(x <= 9) # False (less than or equal to)#Logical Operators
What does (5 > 3) and (10 < 2) evaluate to?
and operator requires BOTH sides to be truthy. The first part (5 > 3) is True, but the second (10 < 2) is False. Since and short-circuits as soon as it finds a falsy value, the whole expression becomes False. A subtle gotcha: Python's and actually returns the falsy value itself (here, False), not always a clean True/False, so 0 and 5 returns 0, not False. They behave the same in if statements, but printing them shows the difference.age = 16
has_permit = True
# and -- both must be True
can_drive = age >= 16 and has_permit
print(can_drive) # True
# or -- at least one must be True
is_weekend = False
is_holiday = True
day_off = is_weekend or is_holiday
print(day_off) # True
# not -- flips True to False and vice versa
is_raining = False
go_outside = not is_raining
print(go_outside) # True#Membership Operators
vowels = "aeiou"
print("a" in vowels) # True
print("x" in vowels) # False
print("z" not in vowels) # TrueThese operators are the building blocks of control flow, which you will learn in the next lesson.
#Code Playground
Tests · Complete each challenge and run to verify. Try printing the type of each variable!
#Putting It All Together
Here is a mini-program that uses everything from this lesson:
This code calls input(). Python here can't pause to ask you, so type the answers below before running — one value per line, in the order the program asks for them.
# City Fact Sheet
city = input("Enter city name: ")
population_millions = float(input("Population (in millions): "))
rainfall_cm = float(input("Annual rainfall (cm): "))
is_coastal = input("Coastal? (yes/no): ").lower() == "yes"
population_total = int(population_millions * 1_000_000)
print("\n--- CITY FACT SHEET ---")
print(f"City: {city}")
print(f"Population: {population_total:,}")
print(f"Rainfall: {rainfall_cm:.1f} cm")
print(f"Coastal: {'Yes' if is_coastal else 'No'}")
print(f"Type check: city is {type(city).__name__}, "
f"population is {type(population_total).__name__}, "
f"rainfall is {type(rainfall_cm).__name__}, "
f"coastal is {type(is_coastal).__name__}")This tiny program demonstrates variables, all five types, type conversion, f-strings, and input. That is a lot of Python in just 15 lines.
#is vs ==: Identity vs Equality
== to compare values. Only use is for checking None:if x is None: # ✅ Correct way to check for None
if x == None: # ❌ Works but wrong styleInteractive Lab
Step through code and watch variables get assigned, updated, and used — see exactly what happens in memory
#Key Takeaways
- Variables are labeled boxes — create them with
=, and Python figures out the type automatically. Usesnake_casefor names - Python has five core types:
int(whole numbers),float(decimals),str(text),bool(True/False), andNone(nothing) - Type conversion is explicit — use
int(),float(),str(),bool()to convert between types.input()always returns a string - F-strings are the best way to format text — write
f"Hello, {name}!"to embed variables directly in strings, with optional formatting like:.2ffor decimals - Operators produce booleans. Comparisons (
==,!=,>,<) and logical operators (and,or,not) are the building blocks of decision-making in code
This program tries to add two values to compute a total, but it crashes with a TypeError. Fix it so it prints the numeric sum.
Sum: 7
Build a temperature converter (F → C)
Ask the user for a temperature in Fahrenheit, then print the equivalent in Celsius (rounded to 1 decimal place). Formula: C = (F - 32) * 5 / 9.
Enter Fahrenheit: 100
100.0F = 37.8CThis code calls input(). Python here can't pause to ask you, so type the answers below before running — one value per line, in the order the program asks for them.
# Temperature converter
fahrenheit_str = input("Enter Fahrenheit: ")
# TODO: convert fahrenheit_str to a float
# TODO: compute Celsius
# TODO: print "<F>F = <C>C" using an f-stringWhat does type('42') return?