Module 1 ยท Lesson 4

Variables and Data Types

๐Ÿ Pythonโฑ 15 min read๐Ÿ“– Core Concept

Variables in Python

A variable is a name that refers to a value in memory. Python uses dynamic typing โ€” you don't declare types, and a variable can hold any type at any time.

# Variable assignment โ€” no type declaration needed x = 42 name = "Alice" price = 9.99 is_active = True # Python infers the type automatically print(type(x)) # <class 'int'> print(type(name)) # <class 'str'> print(type(price)) # <class 'float'> print(type(is_active)) # <class 'bool'> # Multiple assignment a = b = c = 0 # All three point to 0 x, y, z = 1, 2, 3 # Unpack tuple first, *rest = [1, 2, 3, 4] # first=1, rest=[2,3,4]

Naming Rules

The Core Data Types

Integers (int)

Whole numbers, positive or negative. Python integers have no size limit โ€” they can be arbitrarily large.

age = 25 temperature = -10 big_number = 1_000_000 # Underscores for readability (Python 3.6+) factorial_20 = 2432902008176640000 # No overflow! hex_color = 0xFF5733 # Hexadecimal literal binary = 0b1010 # Binary literal (= 10) octal = 0o17 # Octal literal (= 15)

Floats (float)

Decimal numbers. Python uses 64-bit double precision โ€” the same as C's double.

pi = 3.14159265358979 price = 9.99 scientific = 1.5e10 # 15,000,000,000.0 tiny = 2.5e-4 # 0.00025 # The famous floating point gotcha (affects ALL languages) print(0.1 + 0.2) # 0.30000000000000004 โ€” not a Python bug! # Solutions: print(round(0.1 + 0.2, 2)) # 0.3 โ€” for display from decimal import Decimal # For financial calculations result = Decimal("0.1") + Decimal("0.2") print(result) # 0.3 โ€” exact!

Strings (str)

Text data. Python strings are immutable sequences of Unicode characters โ€” they support any language, emoji, and special characters.

greeting = "Hello" name = 'World' # Single or double quotes โ€” your choice multiline = """This is a multiline string""" # Common string operations s = "Python" print(s[0]) # 'P' โ€” indexing (0-based) print(s[-1]) # 'n' โ€” negative indexing from end print(s[1:4]) # 'yth' โ€” slicing [start:end] (end exclusive) print(len(s)) # 6 print(s.upper()) # 'PYTHON' print(s.lower()) # 'python' print(s + " 3") # 'Python 3' โ€” concatenation (use f-strings in practice) print("py" in s) # False (case-sensitive)

Booleans (bool)

Only two values: True and False. Note the capital first letter โ€” Python is case-sensitive.

is_logged_in = True has_permission = False # Boolean operations print(True and False) # False print(True or False) # True print(not True) # False # Comparison operators return booleans print(5 > 3) # True print(5 == 5) # True print(5 != 3) # True # Truthiness โ€” many values evaluate to False: bool(0) # False โ€” zero integer bool(0.0) # False โ€” zero float bool("") # False โ€” empty string bool([]) # False โ€” empty list bool({}) # False โ€” empty dict bool(None) # False โ€” None # Everything else is truthy bool(1) # True bool("hi") # True bool([0]) # True โ€” list with one element (even if that element is 0!)

None โ€” The Absence of Value

None represents "no value" or "not set". It's Python's equivalent of null in other languages.

result = None print(result) # None print(result is None) # True โ€” use 'is', not '==' print(result == None) # True โ€” works but not Pythonic # Common uses def find_user(id): # Returns None if not found return None # No explicit return also gives None user = find_user(999) if user is None: print("User not found")

Type Conversion

# int() โ€” convert to integer int("42") # 42 int(3.9) # 3 (truncates, doesn't round!) int(True) # 1 int(False) # 0 # float() โ€” convert to float float("3.14") # 3.14 float(42) # 42.0 # str() โ€” convert to string str(100) # "100" str(3.14) # "3.14" str(True) # "True" # bool() โ€” convert to boolean bool(0) # False bool(1) # True bool("") # False bool("hello") # True # Safe conversion โ€” handle errors user_input = "not a number" try: number = int(user_input) except ValueError: print(f"'{user_input}' is not a valid integer")

Key Takeaways

Practice Exercises

  1. Create variables for your name, age, height (meters), and whether you enjoy coding. Print each with type().
  2. What is bool("")? What about bool("False")? Run it and explain why.
  3. Write code that converts "3.14" to a float, then to an int. What value do you get?
  4. Given price = 19.99 and quantity = 3, calculate and print the total formatted to 2 decimal places.
  5. Use multiple assignment to swap two variables a = 5 and b = 10 in one line.
โ† The REPL and First Script