What Is a Variable?
Imagine a variable as a labeled box in your computer’s memory. You assign a name to the box and store a value inside it. Whenever you need that value, you can retrieve or update it using the box’s label.
# Examples of variable creation
my_number = 10 # stores the integer 10
my_text = "Hello" # stores the string "Hello"
is_ready = False # stores the boolean value False
Do’s
-
Choose clear, descriptive names:
age
,user_name
,total_price
. -
Use lowercase letters and underscores:
user_count
rather thanUserCount
oruserCount
. -
Keep names concise yet meaningful.
Don’ts
-
Don’t start a name with a digit:
1st_place
is invalid. -
Avoid spaces or hyphens in names: use
my_var
instead ofmy var
ormy-var
. -
Don’t shadow Python keywords or built-ins like
list
,str
,if
, etc
Python’s Built-In Data Types
Python offers several fundamental data types. We’ll cover the most common ones below:
1. Numeric Types: int
& float
-
Integers (
int
) represent whole numbers (e.g.,5
,-3
,0
). -
Floats (
float
) represent numbers with decimal points (e.g.,3.14
,-0.001
).
lives = 3 # int
distance = 12.5 # float
# Arithmetic operations
total = lives * distance
print(total) # outputs: 37.5
You can round floats to a certain precision using round()
:
value = 3.14159
rounded = round(value, 2)
print(rounded) # outputs: 3.14
Do’s: Use int
for counts (e.g., number of tries), float
for measurements (e.g., price, temperature).
Don’ts: Avoid mixing types in arithmetic without conversion: combining a string and an integer without casting will cause an error.
2. Text Type: str
Strings hold sequences of characters, wrapped in quotes:
name = "Alice"
quote = 'Python is fun!'
multiline = """
Line 1
Line 2
Line 3
"""
You can concatenate and repeat strings:
greeting = "Hello, " + name # "Hello, Alice"
echo = "Echo! " * 3 # "Echo! Echo! Echo! "
For formatted text, f-strings are concise and readable:
age = 25
message = f"{name} is {age} years old"
Do’s: Use f-strings for interpolation. Ensure quotes are properly closed.
Don’ts: Avoid mismatched quotes without escaping (e.g., mixing single and double quotes improperly).
3. Boolean Type: bool
Booleans represent truth values: True
or False
. They often result from comparisons:
is_adult = (age >= 18) # True if age is 18 or above
print(is_adult) # True or False
Use booleans in conditional statements:
if is_adult:
print("Access granted")
else:
print("Access denied")
Do’s: Leverage booleans for flow control (if
, while
).
Don’ts: Don’t confuse boolean values with strings (True
vs. "True"
).
4. Collection Types: list
, tuple
, set
, dict
Python’s collection types help you organize multiple values:
-
List (
list
): An ordered, mutable collection that allows duplicates.fruits = ["apple", "banana", "cherry"] fruits.append("date") print(fruits[0]) # "apple"
-
Do’s: Use lists for sequences you’ll modify.
-
Don’ts: Avoid changing a list while looping over it directly.
-
-
Tuple (
tuple
): An ordered, immutable collection.point = (10, 20) x, y = point # tuple unpacking
-
Do’s: Use tuples for fixed data structures or dictionary keys.
-
Don’ts: Don’t try to assign to a tuple element.
-
-
Set (
set
): An unordered collection of unique values.letters = {"a", "b", "c", "a"} print(letters) # {{'a', 'b', 'c'}}
-
Do’s: Use sets to remove duplicates or test membership.
-
Don’ts: Sets don’t support indexing or slicing.
-
-
Dictionary (
dict
): A collection of key–value pairs.student = {"name": "Bob", "score": 85} print(student["name"]) # "Bob" student["score"] = 90
-
Do’s: Use dicts for lookups by key.
-
Don’ts: Avoid using mutable types (like lists) as dictionary keys.
-
Type Conversion & Checking
Convert between types using functions like int()
, float()
, str()
, list()
, etc. Use type()
or isinstance()
to inspect values:
num_str = "123"
num = int(num_str) # convert string to integer
print(type(num)) # <class 'int'>
if isinstance(num, int):
print("num is indeed an integer")
Tip: Always validate or wrap conversions in try/except
to gracefully handle invalid data.
Common Pitfalls & Best Practices
-
Never shadow built-ins: Avoid variable names like
list
,str
,dict
. -
Beware of mutable default arguments: Use
None
and initialize inside the function. -
Don’t modify a list while iterating: Work on a copy or use list comprehensions.
# Bad: mutable default argument
def add_item(item, my_list=[]):
my_list.append(item)
return my_list
# Good: safer default
def add_item(item, my_list=None):
if my_list is None:
my_list = []
my_list.append(item)
return my_list
Always test your code with varied inputs, comment complex logic, and follow consistent naming conventions.