Chapter 2 — Python Basics: Variables, Types, Operators, and I/O
Before analyzing data we need to speak Python fluently. This chapter covers the fundamentals: variables, data types, operators, expressions, type conversion, and input/output formatting — the building blocks of every program that follows.
Learning Objectives
- Declare variables and apply naming rules.
- Use numeric types and arithmetic operators, including
//,%, and**. - Apply operator precedence to evaluate expressions.
- Convert between types and round numbers.
- Manipulate strings with indexing and slicing.
- Use Booleans and comparison operators.
- Format output with f-strings,
format(), andprintoptions. - Read console input and convert it safely.
Prerequisites / Imports
Pure Python — no third-party libraries needed.
import math
1 Syntax, Comments, and Mode
Python uses indentation to define blocks. Comments start with #. You can run Python interactively (the REPL) or as a script. In Jupyter, each cell behaves like a mini-script with shared state.
# This is a comment
message = 'Hello, Data Science' # variable assignment
print(message) # output
Hello, Data Science
2 Variables and Assignment
A variable is a name bound to a value. Identifiers must start with a letter or underscore, are case-sensitive, and cannot be a keyword. Python supports simultaneous assignment.
x = 10
y = 3.5
name = 'Ada'
print(x, y, name)
# Simultaneous assignment (swap without a temp)
a, b = 1, 2
a, b = b, a
print('a =', a, 'b =', b)
10 3.5 Ada a = 2 b = 1
3 Numeric Types and Operators
Python has integers (int), floating-point (float), and complex numbers. Key operators: + - * / // % **. Augmented assignment (+=, -=, ...) updates a variable in place.
print('integer division 7 // 2 =', 7 // 2)
print('modulo 7 % 2 =', 7 % 2)
print('power 2 ** 10 =', 2 ** 10)
print('true division 7 / 2 =', 7 / 2)
integer division 7 // 2 = 3 modulo 7 % 2 = 1 power 2 ** 10 = 1024 true division 7 / 2 = 3.5
total = 0
total += 5 # augmented assignment
total += 10
print('total =', total)
total = 15
4 Operator Precedence
Python follows standard math precedence: ** binds tighter than unary minus, then * / // %, then + -. Use parentheses to make intent explicit.
print('2 + 3 * 4 =', 2 + 3 * 4)
print('(2 + 3) * 4 =', (2 + 3) * 4)
print('-2 ** 2 =', -2 ** 2, '(note: -(2**2))')
print('(-2) ** 2 =', (-2) ** 2)
2 + 3 * 4 = 14 (2 + 3) * 4 = 20 -2 ** 2 = -4 (note: -(2**2)) (-2) ** 2 = 4
5 Type Conversion and Rounding
Convert with int(), float(), str(), bool(). Round with round(x, n).
print(int(3.9), float(5), str(42), bool(0))
print(round(3.14159, 2))
print(round(2.675, 2)) # note floating-point surprise
3 5.0 42 False 3.14 2.67
6 Strings: Indexing and Slicing
Strings are immutable sequences of characters. Index from 0; slice with [start:stop:step].
s = 'DataScience'
print('first:', s[0], 'last:', s[-1])
print('slice [0:4]:', s[0:4])
print('every other:', s[::2])
print('reverse:', s[::-1])
first: D last: e slice [0:4]: Data every other: DtSine reverse: ecneicSataD
7 Booleans and Comparisons
Comparisons return True/False. Combine with and, or, not.
age = 25
print(age >= 18 and age <= 65)
print(not (age < 18))
print(5 > 3, 5 == 5, 5 != 3)
True True True True True
8 Reading Input
input() reads a string from the console. In a notebook it blocks, so we show the pattern with a hardcoded value and demonstrate type conversion.
Code shown for illustration; not executed in this notebook.
# raw = input('Enter your age: ')
# age = int(raw)
# print('Next year you will be', age + 1)
# Safe conversion with error handling (runnable with a fixed value)
raw = '27'
try:
age = int(raw)
print('Parsed age:', age)
except ValueError:
print('That was not an integer.')
Parsed age: 27
9 Output Formatting
f-strings are the modern, readable way to format output. print accepts sep and end.
price = 19.995
qty = 3
print(f'Unit price: ${price:.2f}')
print(f'Total: ${price * qty:,.2f}')
print('2026', '09', '16', sep='-')
print('no newline', end=' ')
print('continued')
Unit price: $20.00 Total: $59.98 2026-09-16 no newline continued
# format() method alternative
print('pi is roughly {:.4f}'.format(math.pi))
pi is roughly 3.1416
10 Named Constants and Style
Use UPPER_CASE for constants to signal they should not change. Follow PEP 8: spaces around operators, descriptive names, lines under ~79 characters.
TAX_RATE = 0.0825
subtotal = 100.0
tax = subtotal * TAX_RATE
print(f'Tax: ${tax:.2f}')
Tax: $8.25
Case Study: A Simple Sales Receipt
Compute a formatted receipt from item prices and quantities, applying tax.
items = [('Widget', 3, 4.50), ('Gadget', 2, 12.75), ('Cable', 5, 1.20)]
TAX_RATE = 0.0825
subtotal = sum(qty * price for _, qty, price in items)
tax = subtotal * TAX_RATE
total = subtotal + tax
print('=== RECEIPT ===')
for name, qty, price in items:
print(f'{name:<8} x{qty} @ ${price:.2f} = ${qty*price:.2f}')
print('-' * 30)
print(f'Subtotal: ${subtotal:.2f}')
print(f'Tax (8.25%): ${tax:.2f}')
print(f'TOTAL: ${total:.2f}')
=== RECEIPT === Widget x3 @ $4.50 = $13.50 Gadget x2 @ $12.75 = $25.50 Cable x5 @ $1.20 = $6.00 ------------------------------ Subtotal: $45.00 Tax (8.25%): $3.71 TOTAL: $48.71
Exercises
- Compute and print the area of a circle with radius 5 using
math.pi. - Evaluate
1 + 2 * 3 ** 2by hand, then verify in Python. - Swap two variables without a temporary variable.
- Convert the string
'3.14'to a float and round it to one decimal. - Slice the string
'DataScience'to get'Science'. - Write an f-string that prints 1234567 with thousands separators.
- Given
celsius = 25, compute and print Fahrenheit with two decimals. - Write a receipt program for two items with a 10% discount before tax.
- Explain why
round(2.675, 2)does not give2.68. - Use
sepandendinprintto output2026/09/16on one line.
Python Data Science: From Foundations to Applications — Chapter 2