Welcome to programming. By the end of this chapter, you'll understand what programming actually is, why we use Python, and you'll have written your first programs that actually DO something. This isn't just theory - you'll be coding within minutes.
Forget everything you've heard about programming being "hard" or requiring a "math brain." Programming is just giving instructions to a computer. If you can follow a recipe, you can program. The only difference is that computers need extremely precise instructions - they won't guess what you meant.
We're starting from absolute zero here. No previous experience required. No prior knowledge assumed. Just you, a computer, and the willingness to learn something new.
What You'll Achieve
By the end of this chapter, you'll be able to write programs that take input from users, process it, and output results. That's the foundation of ALL software ever written - from simple calculators to complex AI systems.
๐ฏ Chapter Goals
- Understand what programming is
- Install Python on your computer
- Write and run your first programs
- Master variables and data types
- Get input and display output
- Use operators for calculations
โฑ๏ธ Time Investment
- Reading: 30-45 minutes
- Coding exercises: 1-2 hours
- Practice projects: 1-2 hours
- Total: ~4 hours for mastery
Don't rush. Understanding beats speed.
What is Programming? (The Real Explanation)
Programming is simply writing instructions for a computer to follow. That's it. No magic, no genius required - just clear, precise instructions. But understanding WHY it works the way it does will make you a much better programmer.
A Brief History (Why This Matters)
In the early days, programmers had to write in binary - patterns of 1s and 0s that computers directly understand. Imagine writing "00110101 01001010" just to add two numbers! This was tedious and error-prone.
Then came assembly language - still low-level, but at least human-readable. "ADD A, B" was better than binary but still tied to specific hardware.
Finally, high-level languages like Python were created. You write code that looks almost like English, and a "compiler" or "interpreter" translates it to machine code. This is why Python is so beginner-friendly - it's designed for humans first, computers second.
# The evolution of "add two numbers":
# Binary (1940s):
# 00000001 00000010 00000011
# Assembly (1950s):
# MOV AX, 5
# ADD AX, 3
# C (1970s):
# int result = 5 + 3;
# Python (1991):
result = 5 + 3
# Python is MUCH easier to read and write!
What Programmers Actually Do
Contrary to what movies show, programmers don't stare at green text on black screens typing furiously. Here's what programming really involves:
1. Understand the Problem
Before writing code, you need to understand what you're trying to solve. What are the inputs? What output do you want? What are the constraints? 80% of programming is thinking, 20% is typing.
# Problem: Calculate tip at restaurant
# Inputs: bill amount, tip percentage
# Output: tip amount, total bill
# Constraints: positive numbers only
2. Break It Into Steps
Big problems become small problems. "Build a website" becomes "show text," "add image," "handle button click." This process is called "decomposition."
# Steps for tip calculator:
# 1. Get bill amount from user
# 2. Get tip percentage from user
# 3. Calculate tip = bill * (percentage/100)
# 4. Calculate total = bill + tip
# 5. Display results
3. Write the Code
Translate your steps into a programming language the computer understands. This is what most people think programming is, but it's actually the easiest part once you understand the problem.
bill = float(input("Bill: $"))
tip_pct = float(input("Tip %: "))
tip = bill * (tip_pct / 100)
total = bill + tip
print(f"Tip: ${tip:.2f}")
print(f"Total: ${total:.2f}")
4. Test and Debug
Your code will have bugs. Finding and fixing them is where most programming time goes. This is normal - even experts debug constantly. Embrace it!
# Test with different inputs:
# Bill: 50, Tip: 20 โ Tip: $10.00 โ
# Bill: 100, Tip: 15 โ Tip: $15.00 โ
# Bill: 0, Tip: 20 โ Tip: $0.00 โ
# Bill: -50, Tip: 20 โ Tip: -$10.00 โ
# Need to handle invalid input!
Programming vs "Coding"
People use these terms interchangeably, but there's a subtle difference:
- Coding: The act of writing code - translating logic into a programming language
- Programming: The entire process - understanding problems, designing solutions, writing code, testing, debugging, and maintaining
You're learning to be a programmer, not just a coder. That means learning to think logically, break down problems, and create solutions - not just memorizing syntax.
The Secret No One Tells Beginners
Professional programmers Google things constantly. They look up syntax they've forgotten, search for solutions to problems, and read documentation every day. Nobody memorizes everything. What matters is understanding concepts and knowing how to find answers. So don't feel bad about looking things up - it's what professionals do!
Why Python?
We're teaching Python for very specific reasons. It's not just "easy" - it's strategically the best choice for beginners who want to build real things. Let me explain why Python dominates both education and industry.
Python vs Other Languages
# ==================== THE SAME LOGIC IN DIFFERENT LANGUAGES ====================
# Python - Clean and readable
if age >= 18:
print("You can vote!")
else:
print("Too young to vote")
# Java - Same logic, more syntax (7 lines โ 11 lines)
public class VotingAge {
public static void main(String[] args) {
if (age >= 18) {
System.out.println("You can vote!");
} else {
System.out.println("Too young to vote");
}
}
}
# C++ - Even more ceremony
#include <iostream>
using namespace std;
int main() {
if (age >= 18) {
cout << "You can vote!" << endl;
} else {
cout << "Too young to vote" << endl;
}
return 0;
}
# JavaScript - Similar to Python but with more punctuation
if (age >= 18) {
console.log("You can vote!");
} else {
console.log("Too young to vote");
}
Python reads almost like English. Less time fighting syntax = more time learning concepts. Notice how Python uses indentation (spaces) instead of curly braces - this forces readable code!
The Numbers Don't Lie
๐ #1 Most Popular
Python is the #1 most popular language on the TIOBE Index and Stack Overflow survey for 3+ years running.
๐ฐ High Salaries
Python developers earn $110K-$150K+ on average. Specialized fields like ML/AI pay even more.
๐ Fastest Growing
Python job postings have grown 456% in the last 5 years. Demand far exceeds supply.
๐ #1 in Education
8 of the top 10 CS programs use Python as their intro language. MIT, Stanford, Berkeley, Harvard...
What Python is Used For
๐ Web Development
Django, Flask, FastAPI - Instagram, Pinterest, Spotify, Netflix, Reddit, Dropbox all use Python backends. Build anything from simple websites to complex applications.
๐ค Data Science & AI
NumPy, Pandas, TensorFlow, PyTorch - Python absolutely dominates machine learning. If you want to work in AI, Python is mandatory.
โ๏ธ Automation
Automate boring tasks - file organization, web scraping, data entry, report generation, email handling. "I'll write a script for that" becomes your superpower.
๐ Hacking & Security
Most security tools are written in Python. Penetration testing, exploit development, malware analysis, network scanning. Ethical hackers love Python.
๐ฎ Game Development
Pygame, Panda3D - great for learning game dev concepts. Many game studios use Python for tools and scripting.
๐ฑ Desktop Applications
Tkinter, PyQt, Kivy - build GUI applications that work on Windows, Mac, and Linux.
The Philosophy of Python
Python was designed with specific principles in mind. Type import this in Python to see "The Zen of Python." Here are the most important principles:
# The Zen of Python (Selected)
Beautiful is better than ugly.
Simple is better than complex.
Readability counts.
There should be one-- and preferably only one --obvious way to do it.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
# Translation:
# Write code that's clean and understandable
# Simple solutions beat clever ones
# Other people (including future you) need to read your code
โ ๏ธ What Python is NOT Good For
No language is perfect for everything:
- Mobile apps: Use Swift (iOS) or Kotlin (Android) instead
- Performance-critical systems: Use C/C++/Rust for games, OS kernels, etc.
- Browser front-end: JavaScript is required for browser code
But Python is excellent for learning, automation, web backends, data science, and scripting - which covers most of what beginners need!
Setting Up Your Environment
Before you can code, you need Python installed and a proper development environment. This takes about 10 minutes and you only do it once. Let's set you up for success.
Installing Python
# ==================== WINDOWS ====================
1. Go to python.org/downloads
2. Click "Download Python 3.x" (latest version)
3. Run the downloaded installer
4. โ ๏ธ CRITICAL: Check "Add Python to PATH" at the bottom! โ ๏ธ
5. Click "Install Now"
6. Wait for installation to complete
7. Click "Close"
# If you forgot to check "Add to PATH":
# Uninstall Python, redownload, and try again
# This is important for running Python from anywhere
# ==================== MAC ====================
# Option 1: Download from python.org (easy)
1. Go to python.org/downloads
2. Download the macOS installer
3. Run installer, follow prompts
# Option 2: Use Homebrew (recommended for developers)
1. Open Terminal
2. Install Homebrew if you don't have it:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
3. Install Python:
brew install python
# Note: Mac comes with Python 2.7 pre-installed (old version)
# Always use python3 command, not python
# ==================== LINUX (Ubuntu/Debian) ====================
sudo apt update
sudo apt install python3 python3-pip python3-venv
# For other distros:
# Fedora: sudo dnf install python3 python3-pip
# Arch: sudo pacman -S python python-pip
Verify Installation
# Open terminal/command prompt and type:
# Windows:
python --version
# Expected output: Python 3.11.4 (or similar)
# Mac/Linux (if python shows 2.x, use python3):
python3 --version
# Expected output: Python 3.11.4
# Check pip (package manager) is installed:
pip --version
# or
pip3 --version
# Expected: pip 23.1.2 from ... (python 3.11)
# ==================== TROUBLESHOOTING ====================
# "python is not recognized" on Windows:
# - Python wasn't added to PATH during installation
# - Fix: Reinstall with "Add to PATH" checked
# "command not found" on Mac/Linux:
# - Try python3 instead of python
# - Or install: sudo apt install python3
# Multiple versions installed:
# - Use py launcher on Windows: py -3.11 script.py
# - Use python3 explicitly on Mac/Linux
Choosing a Code Editor
You can write Python in any text editor, but a good editor makes coding much easier. Here are your options:
๐ VS Code (Recommended)
Free, powerful, and widely used. Install the Python extension for auto-complete, debugging, and more.
Get it: code.visualstudio.com
๐ PyCharm
Made specifically for Python. Community Edition is free. More features but heavier.
Get it: jetbrains.com/pycharm
๐ Jupyter Notebook
Great for data science and learning. Run code in cells, see results immediately.
Install: pip install jupyter
๐ฅ๏ธ IDLE
Comes with Python. Simple but limited. OK for absolute beginners but you'll outgrow it fast.
Get it: Already installed with Python
Your First Python Command (Interactive Mode)
# Open terminal/command prompt and type:
python # (or python3 on Mac/Linux)
# You'll see something like:
Python 3.11.4 (main, Jun 9 2023, 07:30:55)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
# The >>> is the Python prompt - it's waiting for your commands!
# This is called the REPL (Read-Eval-Print-Loop)
# ==================== TRY THESE COMMANDS ====================
>>> print("Hello, World!")
Hello, World!
>>> 2 + 2
4
>>> 10 * 5
50
>>> "Python" + " is " + "awesome!"
'Python is awesome!'
>>> 2 ** 10
1024
>>> exit() # or Ctrl+D to leave
# ==================== WHAT JUST HAPPENED? ====================
# The REPL is perfect for quick experiments
# You type something, Python evaluates it, prints the result
# Then waits for your next input (the Loop part)
# This is great for:
# - Testing ideas quickly
# - Using as a calculator
# - Learning new concepts
# For real programs, you'll write files instead
Pro Tip: Setting Up VS Code for Python
- Download and install VS Code from code.visualstudio.com
- Open VS Code
- Click the Extensions icon (squares) on the left sidebar
- Search "Python" and install the Microsoft Python extension
- Create a new file with .py extension
- VS Code will prompt to select Python interpreter - choose your installed version
- You're ready to code!
Your First Real Program
Let's write a program that's saved in a file, not just typed in the terminal. This is how real software is created - you write code in files, save them, and run them whenever you want.
Creating a Python File
# ==================== STEP 1: CREATE THE FILE ====================
# Open your text editor (VS Code, Notepad++, or even Notepad)
# Create a new file called: hello.py
# The .py extension tells the computer it's a Python file
# ==================== STEP 2: WRITE THE CODE ====================
# Type this code exactly:
print("=====================================")
print(" Welcome to Python Programming! ")
print("=====================================")
print()
print("My name is [Your Name]")
print("I am learning to code!")
print()
print("Let me show you some math:")
print("2 + 2 =", 2 + 2)
print("10 * 5 =", 10 * 5)
print("100 / 4 =", 100 / 4)
print()
print("I just wrote my first Python program!")
# ==================== STEP 3: SAVE THE FILE ====================
# Save it somewhere you can find it (Desktop is fine for now)
# Remember where you saved it!
# ==================== STEP 4: RUN THE PROGRAM ====================
# Open terminal/command prompt
# Navigate to the folder:
cd Desktop # or wherever you saved it
# Run your program:
python hello.py # or python3 hello.py
# ==================== YOU SHOULD SEE: ====================
=====================================
Welcome to Python Programming!
=====================================
My name is [Your Name]
I am learning to code!
Let me show you some math:
2 + 2 = 4
10 * 5 = 50
100 / 4 = 25.0
I just wrote my first Python program!
๐ Congratulations!
You just wrote and ran your first Python program! This is a significant milestone. Every programmer started exactly where you are right now.
Understanding print()
# ==================== THE PRINT FUNCTION ====================
# print() is a built-in function that outputs text to the screen
# Whatever you put in the parentheses gets displayed
print("Text in quotes") # Strings (text) - displays exactly
print(42) # Numbers - displays as-is
print(3.14159) # Decimal numbers (floats)
print(2 + 2) # Expressions - calculates first, then prints
print("Answer:", 2 + 2) # Multiple items (comma-separated)
print() # Empty line (no arguments)
# ==================== QUOTES MATTER ====================
print("Hello") # Double quotes - works
print('Hello') # Single quotes - also works!
print("It's OK") # Double outside, single inside - works
print('Say "Hi"') # Single outside, double inside - works
# This would cause an error:
# print('It's broken') # Python sees: print('It' and gets confused
# ==================== SPECIAL CHARACTERS ====================
print("Line 1\nLine 2") # \n = new line
print("Tab\tHere") # \t = tab
print("Back\\slash") # \\ = literal backslash
print("Say \"Hello\"") # \" = literal quote mark
# ==================== MULTIPLE ARGUMENTS ====================
name = "Alice"
age = 25
print("Name:", name, "Age:", age)
# Output: Name: Alice Age: 25
# Note: Python adds spaces between arguments automatically
# Use sep to change the separator:
print("A", "B", "C", sep="-")
# Output: A-B-C
# Use end to change what comes after:
print("No", end=" ")
print("newline", end="!")
# Output: No newline!
Common Beginner Mistakes
# ==================== MISTAKE 1: FORGETTING QUOTES ====================
print(Hello) # โ Error! Python thinks Hello is a variable
print("Hello") # โ
Correct - quotes indicate text
# ==================== MISTAKE 2: MISMATCHED QUOTES ====================
print("Hello') # โ Error! Started with " but ended with '
print("Hello") # โ
Correct
# ==================== MISTAKE 3: FORGETTING PARENTHESES ====================
print "Hello" # โ Error! (This was Python 2 syntax)
print("Hello") # โ
Correct in Python 3
# ==================== MISTAKE 4: CASE SENSITIVITY ====================
Print("Hello") # โ Error! Python is case-sensitive
PRINT("Hello") # โ Error!
print("Hello") # โ
Correct - lowercase
# ==================== MISTAKE 5: INDENTATION ERRORS ====================
print("Hello") # โ Error! Unexpected indent (space at start)
print("Hello") # โ
Correct - no leading spaces (for now)
Practice: Your Turn!
Exercise 1: About Me
Create about_me.py that prints:
- Your name
- Your age
- Your favorite color
- Why you want to learn Python
Exercise 2: ASCII Art
Create art.py that prints a simple picture using text characters:
/\
/ \
/____\
| |
|__|
Variables: Giving Names to Data
Variables are containers that hold data. You give them a name, and later you can use that name to access the data. This is one of the most fundamental concepts in programming - everything builds on this.
Creating Variables
# ==================== BASIC VARIABLE CREATION ====================
# The = sign is the "assignment operator"
# It puts the value on the right INTO the variable on the left
name = "Alice" # Create variable 'name', assign string "Alice"
age = 25 # Create variable 'age', assign integer 25
height = 5.6 # Create variable 'height', assign float 5.6
is_student = True # Create variable 'is_student', assign boolean True
# ==================== USING VARIABLES ====================
print("Name:", name)
print("Age:", age)
print("Height:", height)
print("Student?", is_student)
# Output:
# Name: Alice
# Age: 25
# Height: 5.6
# Student? True
# ==================== VARIABLES REMEMBER VALUES ====================
# Calculate with variables
birth_year = 2024 - age
print("Born in:", birth_year) # Born in: 1999
# Combine variables
greeting = "Hello, " + name + "!"
print(greeting) # Hello, Alice!
# ==================== NO DECLARATION NEEDED ====================
# In Python, you don't declare variable types
# The type is determined by the value you assign
x = 5 # x is an integer
x = "hello" # now x is a string
x = 3.14 # now x is a float
# This flexibility is called "dynamic typing"
# It's convenient but be careful - know what type you're working with!
Variable Naming Rules
# ==================== VALID VARIABLE NAMES ====================
name = "Alice" # Simple lowercase
user_name = "bob" # Snake_case (Python convention!)
userName = "charlie" # camelCase (works but not Pythonic)
age2 = 30 # Numbers allowed (not at start)
_private = "secret" # Underscore start (convention: internal use)
__dunder__ = "special" # Double underscore (Python internals)
MAX_SIZE = 100 # ALL_CAPS (convention: constants)
# ==================== INVALID VARIABLE NAMES ====================
2fast = "error" # โ Can't START with a number
my-name = "error" # โ No hyphens (Python thinks it's subtraction)
my name = "error" # โ No spaces
class = "error" # โ Can't use reserved words
# ==================== RESERVED WORDS (Can't Use These) ====================
# False, True, None
# and, or, not
# if, elif, else
# for, while, break, continue
# def, return, class, import, from
# try, except, finally, raise
# ... and more
# ==================== PYTHON CONVENTIONS (PEP 8) ====================
# Variables: snake_case (lowercase with underscores)
user_first_name = "John" # โ
Pythonic
userFirstName = "John" # โ ๏ธ Works but not Python style
# Constants: UPPER_CASE
MAX_CONNECTIONS = 100
PI = 3.14159
# Classes: PascalCase (you'll learn this later)
# class UserAccount:
# Private: _single_underscore
_internal_value = "don't touch"
# ==================== BE DESCRIPTIVE ====================
# Bad names (avoid):
x = 5
temp = "john@email.com"
data = [1, 2, 3]
# Good names (prefer):
user_age = 5
user_email = "john@email.com"
scores = [1, 2, 3]
Variables Can Change
# ==================== REASSIGNMENT ====================
# Variables can be given new values at any time
score = 0
print("Starting score:", score) # 0
score = 10
print("After level 1:", score) # 10
score = 50
print("After level 2:", score) # 50
# ==================== USING CURRENT VALUE IN CALCULATION ====================
# You can use a variable's current value to calculate its new value
score = score + 15 # Take current score (50), add 15, store result (65)
print("After bonus:", score) # 65
score = score * 2 # Take current (65), multiply by 2, store (130)
print("Doubled:", score) # 130
# ==================== SHORTHAND OPERATORS ====================
# Python has shortcuts for common operations:
score = 100
score += 10 # Same as: score = score + 10 โ 110
score -= 5 # Same as: score = score - 5 โ 105
score *= 2 # Same as: score = score * 2 โ 210
score /= 3 # Same as: score = score / 3 โ 70.0
score //= 2 # Same as: score = score // 2 โ 35.0
score %= 10 # Same as: score = score % 10 โ 5.0
score **= 2 # Same as: score = score ** 2 โ 25.0
# ==================== MULTIPLE ASSIGNMENT ====================
# Assign same value to multiple variables:
a = b = c = 0
print(a, b, c) # 0 0 0
# Assign different values on one line:
x, y, z = 1, 2, 3
print(x, y, z) # 1 2 3
# Swap variables (Python magic!):
x, y = 10, 20
print(x, y) # 10 20
x, y = y, x # Swap!
print(x, y) # 20 10
Variable Scope (Preview)
Where Variables Exist
Variables have a "scope" - the part of your program where they can be used. For now, know that:
- Variables created at the top level of your script are available everywhere
- Variables created inside functions are only available inside that function
- You must create a variable before you can use it
We'll cover this in depth when we learn about functions in Chapter 03.
# ==================== COMMON MISTAKES ====================
# Mistake 1: Using a variable before creating it
print(undefined_variable) # โ NameError: name 'undefined_variable' is not defined
# Mistake 2: Case matters!
Name = "Alice"
print(name) # โ NameError: 'name' is not defined
print(Name) # โ
Works
# Mistake 3: Forgetting it's assignment, not math equality
x = 5
x = x + 1 # This is NOT saying "x equals x plus 1" (impossible!)
# This is saying "calculate x+1, then store it in x"
Data Types: Different Kinds of Data
Not all data is the same. Numbers, text, and true/false values are fundamentally different, and Python handles them differently. Understanding data types is crucial - many bugs come from mixing types incorrectly.
The Core Data Types
๐ Strings (str)
Text data - characters, words, sentences. Always in quotes (single or double).
name = "Alice"
message = 'Hello!'
long_text = """Multiple
lines of
text"""
empty = ""
๐ข Integers (int)
Whole numbers - positive, negative, or zero. No decimal points.
age = 25
count = -10
big = 1000000
zero = 0
binary = 0b1010 # 10
๐ Floats (float)
Decimal numbers - any number with a decimal point.
price = 19.99
pi = 3.14159
temp = -5.5
sci = 2.5e6 # 2500000.0
โ/โ Booleans (bool)
True or False - only two possible values. Used for logic and decisions.
is_active = True
game_over = False
# Note: Capital T and F!
Deep Dive: Strings
# ==================== CREATING STRINGS ====================
# Single or double quotes - both work
name = "Alice"
name = 'Alice'
# Use opposite quotes to include quotes in text
message = "She said 'Hello'"
message = 'She said "Hello"'
# Triple quotes for multi-line strings
poem = """Roses are red,
Violets are blue,
Python is awesome,
And so are you."""
# ==================== STRING OPERATIONS ====================
# Concatenation (joining)
first = "Hello"
second = "World"
greeting = first + " " + second # "Hello World"
# Repetition
laugh = "Ha" * 3 # "HaHaHa"
line = "-" * 20 # "--------------------"
# Length
message = "Hello"
print(len(message)) # 5
# ==================== ACCESSING CHARACTERS ====================
# Strings are indexed (positions start at 0!)
word = "Python"
# 012345
print(word[0]) # 'P' (first character)
print(word[1]) # 'y' (second character)
print(word[-1]) # 'n' (last character)
print(word[-2]) # 'o' (second to last)
# Slicing (getting parts of a string)
print(word[0:3]) # 'Pyt' (characters 0, 1, 2)
print(word[2:]) # 'thon' (from position 2 to end)
print(word[:4]) # 'Pyth' (from start to position 3)
# ==================== STRING METHODS ====================
text = "Hello World"
print(text.upper()) # "HELLO WORLD"
print(text.lower()) # "hello world"
print(text.title()) # "Hello World"
print(text.replace("World", "Python")) # "Hello Python"
print(text.split()) # ['Hello', 'World'] (list!)
print(text.find("World")) # 6 (starting position)
print(text.count("l")) # 3 (how many times)
print(text.startswith("Hello")) # True
print(text.endswith("!")) # False
# Strip whitespace
messy = " extra spaces "
print(messy.strip()) # "extra spaces"
Deep Dive: Numbers
# ==================== INTEGERS ====================
count = 42
negative = -17
big_number = 1_000_000 # Underscores for readability (Python 3.6+)
# Different bases
binary = 0b1010 # Binary (base 2) = 10
octal = 0o17 # Octal (base 8) = 15
hexadecimal = 0xFF # Hexadecimal (base 16) = 255
# ==================== FLOATS ====================
price = 19.99
tiny = 0.000001
scientific = 2.5e6 # 2.5 ร 10^6 = 2500000.0
negative_exp = 1e-3 # 0.001
# โ ๏ธ Float precision warning!
print(0.1 + 0.2) # 0.30000000000000004 (not exactly 0.3!)
# This is due to how computers represent decimals
# For money, use the decimal module instead
# ==================== INTEGER VS FLOAT DIVISION ====================
print(10 / 3) # 3.3333... (regular division - always float)
print(10 // 3) # 3 (floor division - always rounds down to int)
print(10 % 3) # 1 (modulo - remainder)
# ==================== NUMBER FUNCTIONS ====================
print(abs(-5)) # 5 (absolute value)
print(round(3.7)) # 4 (round to nearest int)
print(round(3.14159, 2)) # 3.14 (round to 2 decimals)
print(min(1, 5, 3)) # 1 (minimum)
print(max(1, 5, 3)) # 5 (maximum)
print(pow(2, 3)) # 8 (2 to the power of 3)
# For more math: import math
import math
print(math.sqrt(16)) # 4.0 (square root)
print(math.floor(3.9)) # 3 (round down)
print(math.ceil(3.1)) # 4 (round up)
Checking Types
# The type() function tells you what type something is
print(type("Hello")) # <class 'str'>
print(type(42)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type(True)) # <class 'bool'>
# ==================== WHY THIS MATTERS ====================
# These look similar but behave VERY differently:
"5" + "5" # "55" (string concatenation)
5 + 5 # 10 (addition)
"5" * 3 # "555" (string repetition)
5 * 3 # 15 (multiplication)
# This causes an error:
# "5" + 5 # โ TypeError: can't add str and int
# ==================== CHECKING TYPES IN CODE ====================
value = "42"
if type(value) == str:
print("It's a string!")
# Better way - isinstance():
if isinstance(value, str):
print("It's a string!")
if isinstance(value, (int, float)):
print("It's a number!")
Converting Types (Casting)
# ==================== TYPE CONVERSION FUNCTIONS ====================
# str() - convert to string
str(42) # "42"
str(3.14) # "3.14"
str(True) # "True"
# int() - convert to integer
int("42") # 42
int(3.99) # 3 (truncates, doesn't round!)
int(True) # 1
int(False) # 0
# int("3.14") # โ Error! Can't convert float string directly
int(float("3.14")) # 3 (convert to float first, then int)
# float() - convert to float
float("3.14") # 3.14
float(42) # 42.0
float("42") # 42.0
# bool() - convert to boolean
bool(1) # True
bool(0) # False
bool("") # False (empty string)
bool("hello") # True (non-empty string)
bool([]) # False (empty list)
bool([1, 2]) # True (non-empty list)
# ==================== ESSENTIAL FOR USER INPUT ====================
# input() ALWAYS returns a string!
age_str = input("Enter your age: ") # User types "25"
print(type(age_str)) # <class 'str'>
# To do math, convert to number:
age_num = int(age_str) # Now it's 25 (integer)
next_year = age_num + 1 # Can do math now!
# Or convert in one step:
age = int(input("Enter your age: "))
# For decimals:
price = float(input("Enter price: "))
โ ๏ธ Type Conversion Errors
Not all conversions work! These will crash your program:
int("hello") # โ ValueError: invalid literal
int("3.14") # โ ValueError: invalid literal (use float() first)
int("") # โ ValueError: invalid literal
Always validate user input or use try/except (covered in a later chapter).
Operators: Doing Things With Data
Operators let you perform actions on data - math, comparisons, logic, and more. They're the verbs of programming. Variables hold nouns (data), operators are the verbs (actions).
Arithmetic Operators (Math)
# ==================== BASIC ARITHMETIC ====================
10 + 3 # 13 Addition
10 - 3 # 7 Subtraction
10 * 3 # 30 Multiplication
10 / 3 # 3.333... Division (always returns float!)
10 // 3 # 3 Floor division (rounds DOWN to integer)
10 % 3 # 1 Modulo (remainder after division)
10 ** 3 # 1000 Exponent (10 to the power of 3)
# ==================== UNDERSTANDING FLOOR DIVISION ====================
# Regular division always gives a float:
15 / 4 # 3.75
# Floor division rounds DOWN to nearest integer:
15 // 4 # 3 (not 4!)
-15 // 4 # -4 (rounds towards negative infinity, not towards zero!)
# ==================== UNDERSTANDING MODULO ====================
# Modulo gives the REMAINDER after division
# Very useful for many programming tasks!
17 % 5 # 2 (17 = 5*3 + 2, remainder is 2)
20 % 5 # 0 (20 = 5*4 + 0, no remainder - evenly divisible)
7 % 2 # 1 (7 is odd)
8 % 2 # 0 (8 is even)
# Common uses of modulo:
# - Check if number is even or odd: n % 2 == 0 means even
# - Wrap around (clocks, circular arrays)
# - Extract digits: 1234 % 10 gives 4 (last digit)
# ==================== ORDER OF OPERATIONS (PEMDAS) ====================
# Just like in math class:
# P - Parentheses first
# E - Exponents
# M/D - Multiplication and Division (left to right)
# A/S - Addition and Subtraction (left to right)
2 + 3 * 4 # 14 (NOT 20! Multiplication first)
(2 + 3) * 4 # 20 (Parentheses first)
2 ** 3 ** 2 # 512 (Exponents: right to left! = 2^9)
10 - 3 - 2 # 5 (Left to right: (10-3)-2)
10 / 2 * 5 # 25.0 (Left to right: (10/2)*5)
# When in doubt, use parentheses! Makes code clearer too.
result = (10 + 5) * (3 - 1) / 2 # Much clearer than 10+5*3-1/2
Comparison Operators
# Comparisons always return True or False (booleans)
# These are fundamental for making decisions in programs
# ==================== THE SIX COMPARISON OPERATORS ====================
10 == 10 # True Equal to (two equals signs!)
10 != 5 # True Not equal to
10 > 5 # True Greater than
10 < 5 # False Less than
10 >= 10 # True Greater than OR equal to
10 <= 5 # False Less than OR equal to
# ==================== CRITICAL DISTINCTION ====================
x = 5 # ASSIGNMENT: Put 5 into the variable x
x == 5 # COMPARISON: Is x equal to 5? Returns True
# This is the #1 mistake beginners make!
# = assigns, == compares
# ==================== COMPARING DIFFERENT TYPES ====================
# Comparing strings (alphabetical order):
"apple" < "banana" # True (a comes before b)
"Apple" < "banana" # True (uppercase < lowercase in ASCII)
"abc" < "abcd" # True (shorter comes first if prefix matches)
# Comparing with different types:
5 == 5.0 # True (int and float can be compared)
"5" == 5 # False (string and int are NEVER equal)
5 > "5" # โ TypeError! Can't compare str and int
# ==================== CHAINING COMPARISONS ====================
# Python allows this (unique to Python!):
x = 5
1 < x < 10 # True (is x between 1 and 10?)
# This is equivalent to:
1 < x and x < 10 # True
# You can chain as many as you want:
1 < 2 < 3 < 4 < 5 # True
Logical Operators (Boolean Logic)
# Combine or modify boolean values
# These are the foundation of decision making
# ==================== AND - Both must be True ====================
True and True # True
True and False # False
False and True # False
False and False # False
# Real example:
age = 25
has_license = True
can_drive = age >= 16 and has_license # True
# ==================== OR - At least one must be True ====================
True or True # True
True or False # True
False or True # True
False or False # False
# Real example:
is_weekend = True
is_holiday = False
day_off = is_weekend or is_holiday # True
# ==================== NOT - Reverses the boolean ====================
not True # False
not False # True
# Real example:
logged_in = False
show_login_button = not logged_in # True
# ==================== COMBINING OPERATORS ====================
age = 25
has_id = True
is_member = False
# Complex condition:
can_enter = (age >= 18 and has_id) or is_member
# Use parentheses for clarity!
# Without them, "and" is evaluated before "or"
# ==================== SHORT-CIRCUIT EVALUATION ====================
# Python stops evaluating as soon as result is known:
# With 'and': if first is False, second isn't evaluated
False and (1/0) # Returns False (doesn't crash!)
# With 'or': if first is True, second isn't evaluated
True or (1/0) # Returns True (doesn't crash!)
# This is useful for safety checks:
name = ""
# This won't crash even if name is empty:
if name and name[0] == "A":
print("Name starts with A")
Assignment Operators
# ==================== BASIC ASSIGNMENT ====================
x = 10 # Simple assignment
# ==================== COMPOUND ASSIGNMENT (AUGMENTED ASSIGNMENT) ====================
# Instead of: x = x + 5
# You can write:
x += 5 # Add and assign (x is now 15)
x -= 3 # Subtract and assign (x is now 12)
x *= 2 # Multiply and assign (x is now 24)
x /= 4 # Divide and assign (x is now 6.0)
x //= 2 # Floor divide and assign (x is now 3.0)
x **= 2 # Power and assign (x is now 9.0)
x %= 4 # Modulo and assign (x is now 1.0)
# ==================== STRING AUGMENTED ASSIGNMENT ====================
message = "Hello"
message += " World" # "Hello World"
message += "!" # "Hello World!"
# ==================== WHY USE THESE? ====================
# 1. Shorter to write
# 2. Clearer intent
# 3. Slightly more efficient (variable accessed once)
# Real example - counting:
count = 0
count += 1 # count is 1
count += 1 # count is 2
count += 1 # count is 3
Membership & Identity Operators
# ==================== MEMBERSHIP: in, not in ====================
# Check if something exists in a collection
"a" in "apple" # True
"x" in "apple" # False
"x" not in "apple" # True
5 in [1, 2, 3, 4, 5] # True
6 in [1, 2, 3, 4, 5] # False
"key" in {"key": "value"} # True (checks keys in dicts)
# Very readable and Pythonic:
if username in admin_list:
grant_access()
# ==================== IDENTITY: is, is not ====================
# Checks if two variables point to the SAME object in memory
# Different from == which checks if values are equal
a = [1, 2, 3]
b = [1, 2, 3]
c = a
a == b # True (same values)
a is b # False (different objects in memory)
a is c # True (c points to same object as a)
# ==================== WHEN TO USE 'is' ====================
# Almost always use == for comparisons
# Use 'is' only for:
# 1. Comparing to None
x = None
if x is None: # Correct
print("x is None")
# if x == None: # Works but not recommended
# 2. Comparing to True/False (rare)
if flag is True: # Explicit boolean check
do_something()
# Why? None, True, False are "singletons" - only one instance exists
Operator Precedence (from highest to lowest)
| ( ) | Parentheses |
| ** | Exponent |
| +x, -x | Unary plus/minus |
| *, /, //, % | Multiplication, division, modulo |
| +, - | Addition, subtraction |
| <, <=, >, >=, ==, != | Comparisons |
| not | Logical NOT |
| and | Logical AND |
| or | Logical OR |
When in doubt, use parentheses to make your intent clear!
Input & Output: Interacting with Users
Programs need to communicate with users. Output displays information (print). Input receives information from users (input). Mastering I/O is essential - every useful program needs to interact with the outside world.
The print() Function - Deep Dive
# ==================== BASIC PRINTING ====================
print("Hello, World!") # Simple text
print(42) # Numbers
print(3.14159) # Floats
print(True) # Booleans
print() # Empty line (blank line)
# ==================== PRINTING MULTIPLE THINGS ====================
name = "Alice"
age = 25
# Multiple arguments (separated by spaces automatically):
print("Name:", name, "Age:", age)
# Output: Name: Alice Age: 25
# How it works:
# - Each argument is converted to string
# - Arguments are joined with spaces (default separator)
# - A newline is added at the end (default ending)
# ==================== CUSTOMIZING PRINT BEHAVIOR ====================
# sep= changes what goes between arguments
print("A", "B", "C") # A B C (default space)
print("A", "B", "C", sep="") # ABC (no separator)
print("A", "B", "C", sep="-") # A-B-C
print("A", "B", "C", sep="\n") # Each on new line
# end= changes what goes at the end (default is newline)
print("Loading", end="") # No newline after
print("...") # Continues on same line
# Output: Loading...
# Useful for progress indicators:
print("Processing", end=" ")
print(".", end=" ")
print(".", end=" ")
print("Done!")
# Output: Processing . . Done!
# ==================== ESCAPE SEQUENCES ====================
# Special characters in strings:
print("Hello\nWorld") # \n = newline
# Output:
# Hello
# World
print("Name:\tAlice") # \t = tab
# Output: Name: Alice
print("She said \"Hi\"") # \" = literal quote
# Output: She said "Hi"
print("C:\\Users\\name") # \\ = literal backslash
# Output: C:\Users\name
print("Line1\nLine2\nLine3")
# Output:
# Line1
# Line2
# Line3
# ==================== RAW STRINGS ====================
# r"..." treats backslashes as literal:
print(r"C:\Users\name") # No need to escape
# Output: C:\Users\name
# Useful for: file paths, regex patterns
The input() Function - Deep Dive
# ==================== BASIC INPUT ====================
name = input("What is your name? ")
# What happens:
# 1. "What is your name? " is displayed (the prompt)
# 2. Program PAUSES and waits
# 3. User types something and presses Enter
# 4. Whatever they typed is returned as a STRING
# 5. That string is assigned to 'name'
print(f"Hello, {name}!")
# ==================== CRITICAL RULE ====================
# input() ALWAYS returns a STRING, even if the user types numbers!
user_input = input("Enter a number: ") # User types: 42
print(type(user_input)) # <class 'str'>
print(user_input + user_input) # "4242" (string concatenation!)
# To do math, you MUST convert:
number = int(user_input) # Now it's the integer 42
print(number + number) # 84 (actual addition!)
# ==================== CONVERTING INPUT ====================
# For integers:
age = int(input("Enter your age: "))
# For decimals:
height = float(input("Enter your height in meters: "))
# For single character (first character only):
initial = input("Enter your first initial: ")[0]
# For yes/no (convert to boolean):
response = input("Continue? (y/n): ")
wants_to_continue = response.lower() == 'y'
# ==================== HANDLING BAD INPUT ====================
# What if the user types "hello" when you ask for a number?
# int("hello") โ CRASH! ValueError
# Solution 1: Validate the input
user_input = input("Enter a number: ")
if user_input.isdigit():
number = int(user_input)
else:
print("That's not a valid number!")
# Solution 2: try/except (covered in later chapter)
try:
number = int(input("Enter a number: "))
except ValueError:
print("Invalid number!")
number = 0 # default value
# ==================== INPUT WITHOUT A PROMPT ====================
# You can call input() with no argument:
data = input() # Just waits, shows nothing
# Usually you want a prompt though for user experience
f-Strings: Modern String Formatting
# ==================== THE PROBLEM f-STRINGS SOLVE ====================
name = "Alice"
age = 25
balance = 1234.5678
# Old way #1 - Concatenation (ugly, error-prone):
print("My name is " + name + " and I am " + str(age) + " years old")
# Old way #2 - Multiple print arguments (limited formatting):
print("My name is", name, "and I am", age, "years old")
# Old way #3 - .format() method (verbose):
print("My name is {} and I am {} years old".format(name, age))
# ==================== f-STRINGS (BEST WAY) ====================
# Put f before the string, use {variable} to insert values:
print(f"My name is {name} and I am {age} years old")
# Why f-strings are better:
# โ Variables are right where they appear in the text
# โ Any expression works inside the braces
# โ Powerful formatting options
# โ More readable and maintainable
# ==================== EXPRESSIONS IN f-STRINGS ====================
# You can put ANY Python expression inside {}:
# Math:
print(f"Next year I'll be {age + 1}")
print(f"5 squared is {5 ** 2}")
# Method calls:
print(f"My name in uppercase: {name.upper()}")
# Conditionals (ternary):
print(f"Status: {'adult' if age >= 18 else 'minor'}")
# Function calls:
print(f"Length of name: {len(name)}")
# ==================== FORMATTING NUMBERS ====================
# {value:format_spec}
price = 19.99
big_num = 1234567
fraction = 0.666666
# Decimal places:
print(f"Price: ${price:.2f}") # $19.99 (2 decimals)
print(f"Precise: {fraction:.4f}") # 0.6667 (4 decimals)
# Thousands separator:
print(f"Population: {big_num:,}") # 1,234,567
# Percentage:
ratio = 0.75
print(f"Complete: {ratio:.0%}") # 75%
print(f"Complete: {ratio:.1%}") # 75.0%
# Padding and alignment:
for i in range(1, 11):
print(f"{i:2} squared = {i**2:3}")
# Output:
# 1 squared = 1
# 2 squared = 4
# 10 squared = 100
# ==================== FORMAT SPEC MINI-LANGUAGE ====================
value = 42
# Width (minimum characters):
print(f"[{value:5}]") # [ 42] (right-aligned by default)
print(f"[{value:<5}]") # [42 ] (left-aligned)
print(f"[{value:^5}]") # [ 42 ] (center-aligned)
print(f"[{value:>5}]") # [ 42] (right-aligned, explicit)
# Fill character:
print(f"[{value:*<5}]") # [42***] (fill with *)
print(f"[{value:0>5}]") # [00042] (fill with 0, zero-padding)
# Signs:
pos = 42
neg = -42
print(f"{pos:+}") # +42 (always show sign)
print(f"{neg:+}") # -42
print(f"{pos: }") # ' 42' (space for positive)
Complete Example Program
# ==================== INTERACTIVE CALCULATOR ====================
# Save this as calculator.py
print("=" * 40)
print(" ๐งฎ PYTHON CALCULATOR ๐งฎ")
print("=" * 40)
print()
# Get user input
print("Enter two numbers to calculate:")
num1 = float(input(" First number: "))
num2 = float(input(" Second number: "))
# Perform calculations
addition = num1 + num2
subtraction = num1 - num2
multiplication = num1 * num2
# Handle division by zero
if num2 != 0:
division = num1 / num2
floor_div = num1 // num2
modulo = num1 % num2
else:
division = "Cannot divide by zero!"
floor_div = "Cannot divide by zero!"
modulo = "Cannot divide by zero!"
# Display results
print()
print("๐ RESULTS:")
print("-" * 40)
print(f" {num1} + {num2} = {addition}")
print(f" {num1} - {num2} = {subtraction}")
print(f" {num1} ร {num2} = {multiplication}")
print(f" {num1} รท {num2} = {division}")
if num2 != 0:
print(f" {num1} // {num2} = {floor_div} (floor division)")
print(f" {num1} % {num2} = {modulo} (remainder)")
print()
print("Thanks for using Python Calculator!")
# ==================== SAMPLE RUN ====================
# ========================================
# ๐งฎ PYTHON CALCULATOR ๐งฎ
# ========================================
#
# Enter two numbers to calculate:
# First number: 17
# Second number: 5
#
# ๐ RESULTS:
# ----------------------------------------
# 17.0 + 5.0 = 22.0
# 17.0 - 5.0 = 12.0
# 17.0 ร 5.0 = 85.0
# 17.0 รท 5.0 = 3.4
# 17.0 // 5.0 = 3.0 (floor division)
# 17.0 % 5.0 = 2.0 (remainder)
#
# Thanks for using Python Calculator!
๐ก Practice Challenge
Create a "Personal Info Card" program that:
- Asks for the user's name, age, city, and favorite hobby
- Calculates birth year from age
- Displays a nicely formatted "card" with all the information
- Uses f-strings for formatting
Try it yourself before looking at solution in Chapter 2!
โ ๏ธ Common Beginner Mistakes
- Forgetting f prefix: print("{name}") prints literally "{name}", not the variable value
- Using wrong quotes: f'Name: {user's_name}' breaks - use f"Name: {user_name}" or escape
- Not converting input: input("Age: ") + 1 crashes - use int(input("Age: ")) + 1
- Forgetting the prompt: input() with no argument gives no indication to the user