Variables and Data Types in the Python Coding Language
By the end, you’ll be able to:
- Create and name variables clearly
- Work with int, float, str, and bool
- Use type(), input(), and operators (+, -, *, /, //, %)
- Format strings with f-strings and handy string methods
- Convert between numbers and strings with int(), float(), str()
Why variables matter in the python coding language
A variable is a labeled box in memory that holds a value. You assign with = (single equals).
age = 29
pi = 3.14159
name = "Riley"
logged_in = True
print(age) # 29
print(name) # Riley
Variables can be reassigned to new values, and even new types:
points = 10 # int
points = 10.0 # now a float
print(type(points)) # <class 'float'>
Naming conventions (clean, readable code)
- Use snakecase: username, total_cost
- Start with a letter or underscore; avoid starting with digits
- Case-sensitive: score and Score are different
- Don’t overwrite built-in names like list or str
- Follow the community’s PEP 8 style guide for readability (e.g., don’t compare booleans to True/False with ==)
is_admin = True
if is_admin:
print("Welcome!")
if is_admin == True:
print("Welcome!")
Meet the core data types: int, float, str, bool
score = 42
print(type(score)) # <class 'int'>
temperature = 21.6
print(type(temperature)) # <class 'float'>
city = "Lisbon"
print(type(city)) # <class 'str'>
is_new = False
print(type(is_new)) # <class 'bool'>
Quick operators you’ll use constantly
x = 10
print(x + 3) # 13
print(x - 3) # 7
print(x * 3) # 30
print(x / 3) # 3.3333333333333335 (true division -> float)
print(x // 3) # 3 (floor division -> int result if both are ints)
print(x % 3) # 1 (remainder)
Floor division // and modulus % work well for breaking amounts into units:
cents = 289
quarters = cents // 25 # 11
leftover = cents % 25 # 14
print(quarters, leftover)
Getting input and checking types
input() collects text from the user as a string. Convert to numbers for math.
price_text = input("Enter price: ") # e.g., 12.99
price = float(price_text) # convert to float
qty = int(input("Quantity: ")) # convert immediately to int
subtotal = price * qty
print("Subtotal:", subtotal)
print(type(price_text)) # <class 'str'>
print(type(subtotal)) # <class 'float'>
Check or confirm a variable’s type with type():
print(type(qty)) # <class 'int'>
Strings you’ll use every day (plus f-strings)
Strings are sequences of characters. You’ll polish lots of input with these:
msg = " hello, world! "
print(msg.upper()) # " HELLO, WORLD! "
print(msg.lower()) # " hello, world! "
print(msg.strip()) # "hello, world!" (removes surrounding spaces)
print(len(msg)) # 17
print(msg.replace("world", "Python")) # " hello, Python! "
f-strings format values cleanly inside text:
name = "Riley"
score = 42
print(f"{name} scored {score} points") # Riley scored 42 points
price = 12.5
print(f"Total: ${price:.2f}") # Total: $12.50 (2 decimal places)
Type conversions make your data play nicely together:
n = int("10") # 10
pi_text = str(3.14159) # "3.14159"
height = float("1.75") # 1.75
Tip: These basics power conditions and loops in Control Flow Fundamentals for Python Coding. They also pair perfectly with functions later in Functions and Modules for Python Coding Beginners.
A quick note on style and readability
Readable code is easier to debug. The human-friendly summary of style lives at PEP 8 (for humans). As you practice python coding, small habits like clear names and consistent spacing add up.
Gotchas (so you don’t get tripped up)
- Float precision: 0.1 + 0.2 may show 0.30000000000000004 because floats use binary fractions. For display, use round() or format: f"{0.1 + 0.2:.2f}" -> 0.30.
- Newlines: print() ends with a newline by default. Control it with end="":
print("Hello", end="") print(" world!") # prints on the same line
And in strings, \n inserts a line break: "Line1\nLine2". input() returns what the user typed (no trailing newline), so strip() is usually for removing spaces, not the Enter key.
Before you tackle the exercises. If you don’t have Python installed, you can run every snippet in a browser using one of these top Python online IDEs.
Practice: small wins you can code in minutes
Each exercise is short, practical, and shows expected output so you can compare. Try them in your editor or an online IDE.
1) Rectangle area calculator
Prompt the user for width and height. Then compute the area.
width = float(input("Width (m): "))
height = float(input("Height (m): "))
area = width * height
print(f"Area: {area:.2f} square meters")
Expected output example:
Width (m): 3
Height (m): 4.5
Area: 13.50 square meters
2) String formatting practice
Ask for a name and favorite hobby. Tidy the text, and print a friendly sentence.
raw_name = input("Your name: ") # try typing spaces before/after
hobby = input("Favorite hobby: ")
name = raw_name.strip().title() # e.g., "rILEY" -> "Riley"
print(f"Nice to meet you, {name}! {hobby.strip().upper()} sounds fun.")
Expected output example:
Your name: rIlEy
Favorite hobby: python coding
Nice to meet you, Riley! PYTHON CODING sounds fun.
3) Change maker with // and %
Turn cents into dollars and leftover cents using floor division and modulus.
cents = int(input("Enter cents: "))
dollars = cents // 100
leftover = cents % 100
print(f"You have ${dollars} and {leftover} cents")
Expected output example:
Enter cents: 289
You have $2 and 89 cents
For more practice with variables and data types, work through these python exercises beginners.
Where this fits in the bigger picture
- Variables and types underpin if-statements and loops in the next chapter: Control Flow Fundamentals for Python Coding.
- You’ll pass values into functions and return results in Functions and Modules for Python Coding Beginners.
- Soon you’ll store and process collections in Data Structures and Files in Python Coding and combine these skills in Build a Mini Project in the Python Coding Language.
Summary
- Variables label values; assignment uses =
- Core types: int, float, str, bool
- type() inspects a value; input() reads text you often convert with int()/float()
- Operators: +, -, *, /, //, %
- Strings: strip(), upper(), lower(), replace(), len(), and f-strings for formatting
- Gotchas: float precision and print() newlines
Next up, you’ll start making decisions with if/else in Control Flow Fundamentals for Python Coding. You’re building a solid foundation in the python coding language.
Additional Resources
- PEP 8 style guide (official): Community conventions for naming, formatting, and boolean comparisons that keep your code clean and readable.