Variables in Python
Variable
A named container that stores a value in your computer's memory. Think of it as a labeled box where you can put data.
Unlike some languages, Python variables do not need type declarations. Python figures out the type automatically.
Variables are the foundation of programming. They let you store, modify, and retrieve data. In Python, creating a variable is as simple as giving it a name and assigning a value.
Real-World Analogy
Think of variables like labeled boxes in a storage room:
- The label is the variable name (like "shoes" on a box)
- The contents is the value stored inside (like the actual shoes)
- You can open the box to see what is inside (read the variable)
- You can replace the contents with something new (change the value)
- The label stays the same even if you change what is inside
Creating Variables
Use the equals sign (=) to assign a value to a variable. The equals sign in programming means "store this value in this name" - it is not the same as math equality:
# Creating variables
name = "Alice" # String variable
age = 25 # Integer variable
height = 5.6 # Float variable
is_student = True # Boolean variable
# Print variables
print(name) # Alice
print(age) # 25
print(height) # 5.6
print(is_student) # True
Changing Variable Values
Variables can change! That is why they are called "variables" - their values can vary:
# Variables can change their values
score = 0
print(score) # 0
score = 10 # Changed the value
print(score) # 10
score = score + 5 # Add 5 to current value
print(score) # 15
# You can even change the type (but be careful!)
my_data = 100 # Integer
print(my_data) # 100
my_data = "Hello" # Now it is a string
print(my_data) # Hello
Multiple Variables at Once
Python lets you create several variables in one line:
# Assign multiple variables at once
x, y, z = 1, 2, 3
print(x) # 1
print(y) # 2
print(z) # 3
# Give the same value to multiple variables
a = b = c = 0
print(a, b, c) # 0 0 0
# Swap two variables (Python makes this easy!)
first = "apple"
second = "banana"
first, second = second, first
print(first) # banana
print(second) # apple
Variable Naming Rules
Valid Names
my_variable- snake_case (recommended)myVariable- camelCase_private- starts with underscorename2- contains numbersMAX_VALUE- constants (uppercase)
Invalid Names
2name- cannot start with numbermy-variable- no hyphens allowedmy variable- no spaces allowedclass- reserved keywordfor- reserved keyword
user_age instead of x. Your future self will thank you!
Common Beginner Mistakes
Mistake: Using before defining
print(message) # Error!
message = "Hi"
You must create a variable before using it.
Correct: Define first, then use
message = "Hi" # Create first
print(message) # Then use
Always define variables before you use them.
Name, name, and NAME are three different variables.
Basic Data Types
Data types tell Python what kind of data you are working with. Just like in real life, you handle numbers differently than text - you can add numbers together, but you cannot add "hello" + 5 (that does not make sense!). Python has several built-in data types, and understanding them is essential for writing correct programs.
Why Data Types Matter: Imagine telling someone "add 5 to your phone number." That is confusing because a phone number is text (you do not do math with it), not a number for calculations. Python needs to know the type so it can handle your data correctly.
int
Whole numbers
42, -17, 0
float
Decimal numbers
3.14, -0.5, 2.0
str
Text strings
"Hello", 'Python'
bool
True or False
True, False
Understanding Each Type
Integers (int) - Whole Numbers
Integers are whole numbers without decimal points. They can be positive, negative, or zero.
# Integer examples
age = 25 # Positive integer
temperature = -10 # Negative integer
count = 0 # Zero is also an integer
big_number = 1000000 # Python handles big numbers easily
print(age + 5) # 30 (math works!)
Floats (float) - Decimal Numbers
Floats are numbers with decimal points. Use them for precise measurements, prices, or any fractional values.
# Float examples
price = 19.99 # Money usually needs decimals
pi = 3.14159 # Mathematical constants
temperature = 98.6 # Body temperature
percentage = 0.85 # 85% as a decimal
# Be careful: division always returns a float!
result = 10 / 4 # 2.5 (not 2!)
print(type(result)) # <class 'float'>
Strings (str) - Text
Strings are sequences of characters (text). They must be wrapped in quotes - either single (') or double (").
# String examples - both quote styles work
name = "Alice" # Double quotes
city = 'New York' # Single quotes
# Use the other quote type to include quotes in your string
message = "She said 'hello'"
quote = 'He replied "goodbye"'
# Empty string (no characters)
empty = ""
# Strings can be joined (concatenated)
full_name = "John" + " " + "Doe"
print(full_name) # John Doe
Booleans (bool) - True or False
Booleans represent yes/no, on/off, or true/false values. They are essential for making decisions in code.
# Boolean examples (note the capital T and F!)
is_student = True # Yes, they are a student
has_license = False # No, they do not have a license
# Booleans come from comparisons
age = 20
is_adult = age >= 18 # True (20 is greater than or equal to 18)
print(is_adult) # True
# Common use: checking conditions
is_raining = True
if is_raining:
print("Bring an umbrella!")
Checking Data Types
Not sure what type a variable is? Use the type() function to find out:
# Check data types with type()
age = 25
price = 19.99
name = "Python"
is_active = True
print(type(age)) # <class 'int'>
print(type(price)) # <class 'float'>
print(type(name)) # <class 'str'>
print(type(is_active)) # <class 'bool'>
# Useful for debugging!
mystery = "42"
print(type(mystery)) # <class 'str'> - it is text, not a number!
Type Conversion (Casting)
Sometimes you need to convert data from one type to another. This is called "casting" or "type conversion":
# Converting strings to numbers
user_input = "42" # This is a string (text)
number = int(user_input) # Convert to integer: 42
decimal = float(user_input) # Convert to float: 42.0
print(number + 10) # 52 (now we can do math!)
# Converting numbers to strings
age = 25
age_text = str(age) # Convert to string: "25"
message = "I am " + age_text + " years old"
print(message) # I am 25 years old
# Converting float to int (WARNING: this truncates, not rounds!)
price = 9.99
whole = int(price) # 9 (drops the .99, does not round to 10!)
print(whole) # 9
text = "hello"
number = int(text) # ERROR! "hello" is not a number
- When getting input from users (input() always returns a string)
- When reading data from files (usually comes as strings)
- When combining numbers with text in messages
- When you need to do math with string data
Operators
Operators are special symbols that perform operations on values. Just like in math class, you can add, subtract, multiply, and divide. But Python also has operators for comparing values, combining conditions, and more!
Think of operators like buttons on a calculator:
Each button (operator) does something specific to the numbers you give it. The + button adds,
the - button subtracts, and so on.
Arithmetic Operators
These operators do math, just like you learned in school:
| Operator | Name | Example | Result |
|---|---|---|---|
+ |
Addition | 5 + 3 | 8 |
- |
Subtraction | 5 - 3 | 2 |
* |
Multiplication | 5 * 3 | 15 |
/ |
Division | 5 / 3 | 1.666... |
// |
Floor Division | 5 // 3 | 1 |
% |
Modulus (Remainder) | 5 % 3 | 2 |
** |
Exponentiation | 5 ** 3 | 125 |
- Floor division (//): Divides and rounds DOWN to nearest whole number. Useful for counting whole items.
- Modulus (%): Gives the REMAINDER after division. Useful for checking if a number is even/odd.
- Exponentiation (**): Raises to a power. 2**3 means 2 x 2 x 2 = 8.
Practical Examples
# Real-world arithmetic examples
# Calculate total price
price = 29.99
quantity = 3
total = price * quantity
print(f"Total: ${total}") # Total: $89.97
# Split a bill
bill = 85.50
people = 4
each_pays = bill / people
print(f"Each person pays: ${each_pays}") # $21.375
# How many full boxes needed?
items = 25
items_per_box = 6
full_boxes = items // 6 # 4 (floor division)
leftover = items % 6 # 1 (remainder)
print(f"{full_boxes} full boxes, {leftover} items left over")
# Check if number is even or odd
number = 17
if number % 2 == 0:
print("Even")
else:
print("Odd") # Odd (17 divided by 2 has remainder 1)
Comparison Operators
Comparison operators compare two values and return True or False.
They are essential for making decisions in your code:
x = 10
y = 5
# Equal to (use == not =)
print(x == y) # False - is 10 equal to 5? No!
print(x == 10) # True - is 10 equal to 10? Yes!
# Not equal to
print(x != y) # True - is 10 different from 5? Yes!
# Greater than / Less than
print(x > y) # True - is 10 greater than 5? Yes!
print(x < y) # False - is 10 less than 5? No!
# Greater than or equal / Less than or equal
print(x >= 10) # True - is 10 greater than or equal to 10? Yes!
print(x <= y) # False - is 10 less than or equal to 5? No!
= (assignment) with == (comparison)!
x = 5means "store 5 in x"x == 5means "is x equal to 5?"
Logical Operators
Logical operators let you combine multiple conditions. Think of them as connecting words:
and
Both conditions must be True
"I need coffee AND breakfast"
(need both)
or
At least one condition must be True
"I will have tea OR coffee"
(either works)
not
Flips True to False (and vice versa)
"I am NOT hungry"
(opposite)
Here is how logical operators work in practice with real-world scenarios:
# Logical operators in action
a = True
b = False
print(a and b) # False (both must be True, but b is False)
print(a or b) # True (at least one is True, and a is True)
print(not a) # False (opposite of True)
print(not b) # True (opposite of False)
# Real-world examples
age = 25
has_license = True
has_car = False
# Can you drive? Need to be 18+ AND have a license
can_drive = age >= 18 and has_license
print(f"Can drive: {can_drive}") # True
# Can you get to work? Need a car OR a bus pass
has_bus_pass = True
can_commute = has_car or has_bus_pass
print(f"Can commute: {can_commute}") # True
# Is the store closed?
is_open = False
is_closed = not is_open
print(f"Store closed: {is_closed}") # True
Assignment Operators
These operators assign values to variables. The shorthand versions save typing and make your code cleaner:
# Basic assignment
score = 0
# Long way vs shorthand
score = score + 10 # Add 10 to score
score += 10 # Same thing, shorter!
# All shorthand operators
x = 10
x += 5 # x = x + 5 -> 15
x -= 3 # x = x - 3 -> 12
x *= 2 # x = x * 2 -> 24
x /= 4 # x = x / 4 -> 6.0
x //= 2 # x = x // 2 -> 3.0
x **= 2 # x = x ** 2 -> 9.0
Indentation
Indentation
The whitespace at the beginning of a line that defines code blocks. In Python, indentation is not just for readability - it is required!
Unlike languages that use curly braces {}, Python uses indentation to group statements.
Python uses indentation (usually 4 spaces) to define code blocks. This makes Python code clean and readable, but incorrect indentation causes errors. This is one of the first things that trips up beginners, so pay close attention!
Think of indentation like an outline: In a written outline, you indent sub-points under main points. Python works the same way - indented code "belongs to" the line above it.
Why Does Python Use Indentation?
Many programming languages use curly braces {} to group code. Python uses spaces instead, which makes code cleaner and forces you to write readable code:
Other Languages (JavaScript)
if (true) {
console.log("Braces define blocks");
console.log("Indentation is optional");
}
Python
if True:
print("Indentation defines blocks")
print("No braces needed!")
The Rules of Indentation
Rule 1: Use 4 Spaces
The Python community uses 4 spaces as the standard. Most editors automatically convert the Tab key to 4 spaces.
Rule 2: Be Consistent
All code in the same block must have the same indentation. Do not mix tabs and spaces!
Rule 3: Indent After Colons
Lines ending with : (if, for, while, def, class) require the next line to be indented.
Rule 4: Unindent to End Blocks
To end a code block, simply stop indenting. The next line with less indentation starts a new block.
Visual Example
# Correct indentation example
age = 20
if age >= 18: # Line ends with : so indent next line
print("You are an adult") # 4 spaces in
print("You can vote") # Same level = same block
if age >= 21: # Nested if - ends with : so indent more
print("You can also drink") # 8 spaces in (4 + 4)
print("Back to first if block") # Back to 4 spaces
print("Outside the if") # No indentation = outside the if block
Common Indentation Errors
Error 1: No Indentation
if True:
print("Missing indent!") # IndentationError!
Python expects indented code after the colon.
Error 2: Inconsistent Indentation
if True:
print("Four spaces")
print("Two spaces") # IndentationError!
All lines in a block must have the same indent.
Error 3: Unexpected Indent
name = "Alice"
print(name) # IndentationError!
You cannot indent for no reason!
Correct Version
if True:
print("Properly indented!")
print("Same level - works!")
Consistent 4-space indentation.
Input and Output
Every program needs to communicate with the outside world! Output lets your program display information to users, while input lets users provide information to your program. These two functions are among the most commonly used in Python.
Think of it like a conversation:
Your program "speaks" using print() and "listens" using input().
Together, they create interactive programs!
The print() Function
The print() function displays text on the screen. It is your program's way of
talking to the user:
# Basic printing - just put text in quotes
print("Hello, World!") # Hello, World!
print('Single quotes work too') # Single quotes work too
# Print variables
name = "Alice"
age = 25
print(name) # Alice
print(age) # 25
# Print multiple things at once (separated by spaces)
print("Name:", name, "Age:", age) # Name: Alice Age: 25
F-Strings: The Best Way to Print Variables
F-strings (formatted strings) are the modern, recommended way to include variables in text.
Just put an f before the quotes and wrap variables in curly braces {}:
# F-strings - put f before the quotes, variables in {}
name = "Alice"
age = 25
# Much cleaner than concatenation!
print(f"My name is {name} and I am {age} years old.")
# Output: My name is Alice and I am 25 years old.
# You can even do calculations inside {}
print(f"Next year I will be {age + 1}") # Next year I will be 26
# Format numbers nicely
price = 19.99
print(f"Total: ${price:.2f}") # Total: $19.99 (2 decimal places)
pi = 3.14159265359
print(f"Pi is approximately {pi:.2f}") # Pi is approximately 3.14
Advanced print() Options
# Change what separates printed items (default is space)
print("A", "B", "C") # A B C (default: space)
print("A", "B", "C", sep="-") # A-B-C
print("A", "B", "C", sep="") # ABC (no separator)
print("A", "B", "C", sep="\n") # Each on new line
# Change what comes at the end (default is newline)
print("Hello", end=" ") # Does NOT go to new line
print("World") # Continues on same line
# Output: Hello World
# Print on same line in a loop
for i in range(5):
print(i, end=" ") # 0 1 2 3 4
The input() Function
The input() function pauses your program and waits for the user to type something.
It is how your program can have a conversation with the user:
# Basic input - displays prompt and waits for user
name = input("What is your name? ")
print(f"Hello, {name}!")
# When you run this, it shows:
# What is your name? _ (cursor waits here)
# User types: Alice
# Output: Hello, Alice!
input()
function ALWAYS returns a string, even if the user types a number! If you need to do math,
you must convert it first.
# input() always returns a string - even numbers!
age_string = input("Enter your age: ") # User types: 25
print(type(age_string)) # <class 'str'> - it's a string!
# print(age_string + 5) # ERROR! Cannot add string + number
# Convert to int for whole numbers
age = int(input("Enter your age: "))
print(f"Next year you will be {age + 1}") # Works!
# Convert to float for decimals
height = float(input("Enter your height in meters: "))
print(f"Your height is {height} meters")
# Common pattern: get input and convert in one line
price = float(input("Enter the price: $"))
quantity = int(input("How many? "))
total = price * quantity
print(f"Your total is ${total:.2f}")
Complete Interactive Example
Here is a complete example showing input and output working together:
# A simple greeting program
print("Welcome to the Greeting Program!")
print("-" * 30) # Print 30 dashes as a separator
# Get information from the user
name = input("What is your name? ")
age = int(input("How old are you? "))
city = input("What city do you live in? ")
# Display a personalized message
print() # Empty line for spacing
print(f"Nice to meet you, {name}!")
print(f"So you are {age} years old and live in {city}.")
print(f"In 10 years, you will be {age + 10}!")
print()
print("Thanks for using this program. Goodbye!")
ValueError. For now, just be
careful - you will learn error handling later!
age = int(input("Enter age: ")) # User types "twenty"
# ERROR: ValueError: invalid literal for int()
Key Takeaways
Variables
Named containers that store values. Use descriptive snake_case names.
Data Types
int, float, str, and bool are the basic types. Use type() to check.
Operators
Arithmetic (+, -, *, /), comparison (==, !=), and logical (and, or, not).
Comments
Use # for single-line and triple quotes for multi-line comments.
Indentation
Use 4 spaces for code blocks. Indentation is mandatory in Python!
Input/Output
print() displays output, input() gets user input (returns string).
Knowledge Check
Test your understanding of Python basic syntax:
Which of these is a valid Python variable name?
What is the result of 17 // 5 in Python?
What does the input() function return?
How many spaces should you use for indentation in Python?
What is the output of: print(type(3.14))?
What does the expression (True and False) or True evaluate to?
Comments
Comments are notes in your code that Python completely ignores when running your program. They are written for humans - to help you (and others) understand what your code does and why you wrote it that way. Think of comments as sticky notes you leave for your future self!
Why write comments? Imagine reading code you wrote 6 months ago. Without comments, you might forget why you did things a certain way. Comments save time and prevent confusion!
Single-Line Comments
Use the hash symbol (#) to start a comment. Everything after the # on that line is ignored:
Multi-Line Comments
For longer explanations, use triple quotes ("""). These are also called "docstrings" when used to document functions:
Good vs Bad Comments
Bad Comments
These comments just repeat what the code says!Good Comments
These explain WHY, not just what!