What are Variables?
What are Variables? The Building Blocks of Your Code
Imagine you're baking a cake. You need sugar, flour, eggs, and milk. Instead of remembering the exact amount of each ingredient every time you use it (e.g., "700 grams of white crystalline substance," "500 grams of finely ground grain"), you label containers: one for "sugar," one for "flour," and so on. When the recipe says "add sugar," you grab the container labeled "sugar." If you run out, you refill the "sugar" container, and it still holds sugar, just a different amount.
In programming, variables serve a very similar purpose. They are named storage locations that hold data in a computer's memory. Instead of remembering the exact memory address where a piece of information resides (which would be incredibly complex and error-prone!), you give that storage location a human-readable name – a variable name.
Why Do We Need Variables?
Variables are absolutely fundamental for several reasons:
- Storing Information: They allow your program to remember pieces of data, like a user's name, a calculated score, the current temperature, or the number of items in a shopping cart. Without variables, your program would be like a person with no short-term memory!
- Reusability: Once you store a value in a variable, you can refer to it multiple times throughout your code without having to type the value out repeatedly. This makes your code cleaner, shorter, and less prone to errors.
- Flexibility: The value stored in a variable can change as your program runs. This is crucial for dynamic applications that respond to user input or changing conditions. For instance, a variable
scorecan start at 0 and increase as a player earns points, orcurrent_timecan update every second. - Readability: Giving meaningful names to your variables makes your code much easier for you (and others) to understand. Imagine trying to debug code where
xholds a customer's name,yholds their age, andzholds their order total.customer_name,customer_age, andorder_totalare far clearer!
{{VISUAL: diagram: an analogy showing a variable as a labeled container (e.g., "age") holding a specific data value (e.g., "30").}}
Declaring and Assigning Variables in Python
Python makes working with variables incredibly straightforward. Unlike some other programming languages, you don't need to explicitly "declare" the type of data a variable will hold before using it. You simply assign a value to a name using the equals sign (=), which is called the assignment operator. Python is smart enough to figure out the data type on its own.
Let's look at an example:
# Assigning an integer (whole number) value
age = 30
# Assigning a string (text) value
user_name = "Alice"
# Assigning a floating-point (decimal number) value
price = 19.99
# Assigning a boolean (True/False) value
is_active = True
In the examples above:
age,user_name,price, andis_activeare our variable names. These are the labels.30,"Alice",19.99, andTrueare the values being stored. These are the contents.- The
=symbol assigns the value on the right to the variable name on the left.
Once a variable has been assigned a value, you can use its name to access that value anywhere in your code:
print(age) # Output: 30
print(user_name) # Output: Alice
# You can even use variables in calculations!
total_cost = price * 2
print(total_cost) # Output: 39.98 (19.99 * 2)
What's happening "under the hood"?
When you write age = 30, Python doesn't just put the number 30 into a box named age. Instead, Python creates an "object" representing the number 30 somewhere in your computer's memory. Then, the variable age acts like a label or a reference that points to that object.
If you then do age = 31, Python creates a new object for the number 31 and makes the variable age point to that new object. The old 30 object might still exist in memory for a short while, but age no longer refers to it. Python's memory management (called "garbage collection") eventually cleans up objects that are no longer referenced by any variable, freeing up memory.
{{VISUAL: diagram: a sequence showing a variable 'x' initially pointing to value '10' in memory, and then after reassignment 'x' pointing to a different value '20' in memory, illustrating how references change.}}
Variable Naming Rules and Best Practices
Choosing good, descriptive names for your variables is a hallmark of good programming. It makes your code much easier to read, understand, and maintain, especially as your programs grow in complexity. Python has specific rules you must follow and widely accepted conventions you should follow for naming variables.
Rules (Must Follow):
- Start with a Letter or Underscore: Variable names must begin with a letter (a-z, A-Z) or an underscore (
_). They cannot start with a number.valid_name = 10_private_var = "secret"1st_number = 5(Invalid! This will cause aSyntaxError.)
- Alphanumeric Characters and Underscores: The rest of the variable name can consist of letters, numbers (0-9), and underscores. Spaces are not allowed.
my_variable_name = "hello"item_count_2 = 100my variable = "nope"(Invalid! This will cause aSyntaxError.)
- Case-Sensitive: Python variable names are case-sensitive.
age,Age, andAGEare considered three different variables.my_variable = 5My_Variable = 10# This is a different variable!MY_VARIABLE = 15# Yet another different variable!
- Reserved Keywords: You cannot use Python's reserved keywords (like
if,for,while,class,def,True,False,None) as variable names. These words have special meanings in Python, and trying to redefine them would confuse the interpreter. (Don't worry, you'll learn about these later!)
Best Practices (Should Follow):
- Descriptive Names: Choose names that clearly indicate the purpose or content of the variable. This is the most important best practice!
customer_nameis far better thancnorx.temperature_celsiusis better thantemp.
- Lowercase with Underscores (Snake Case): The widely accepted convention in Python (as per the PEP 8 style guide) is to use lowercase letters with words separated by underscores for readability. This is called "snake_case".
user_input_stringtotal_items_in_cart- Avoid
camelCase(e.g.,userInputString) which is common in JavaScript or Java, but not idiomatic Python for variables.
- Avoid Single Letters (Mostly): While
x,y,i,jare sometimes acceptable as temporary loop counters or mathematical variables, avoid using them for important data that needs to be understood outside a very small context. - Be Consistent: Once you choose a naming style (like
snake_case), stick with it throughout your project. Consistency makes your code predictable and easier to follow.
{{VISUAL: diagram: a comparison table showing examples of good (snake_case, descriptive) vs. bad (camelCase, vague, starting with numbers, using keywords) variable names in Python.}}
Key Takeaways
- Variables are named containers for data. They allow your program to store, reference, and manipulate information efficiently.
- You assign values to variables using the
=operator in Python. - Python variables are dynamically typed, meaning you don't explicitly state their data type; Python infers it from the value you assign.
- Follow naming rules (starts with letter/underscore, alphanumeric) and best practices (snake_case, descriptive) for clean, readable code that others (and your future self!) will appreciate.
Understanding variables is the very first step toward writing useful and dynamic Python programs. They are the fundamental building blocks upon which all more complex operations are built. In the next pages, we'll explore the different types of data you can store in these variables!
Numbers: Int & Float
Numbers: Int & Float
Welcome back, future Pythonista! In our previous page, we dipped our toes into the world of variables. Now, it's time to dive into the most fundamental building blocks of almost any program: numbers. Python provides two primary numeric types for handling numerical data: integers (int) and floating-point numbers (float). Understanding these is crucial for everything from simple calculations to complex data analysis.
Let's break them down.
Integers (int): The Whole Story
Imagine counting apples, tracking a score in a game, or numbering pages in a book. For these scenarios, you're dealing with whole numbers – no fractions, no decimals. In Python, these are represented by the int data type.
What they are: Integers are positive or negative whole numbers (including zero) without any decimal component. Python's integers have arbitrary precision, meaning they can be as large as your computer's memory allows, unlike some other programming languages that limit integer size.
Declaring Integers: Assigning an integer value to a variable is straightforward:
# Positive integer
score = 100
# Negative integer
temperature = -5
# Zero
count = 0
# A really large integer (Python handles it effortlessly!)
population = 7800000000
To verify the type of a variable, Python offers the built-in type() function:
print(type(score))
print(type(temperature))
This will output:
<class 'int'>
<class 'int'>
{{VISUAL: diagram: A comparison table illustrating key characteristics and typical use cases for Python's int and float data types.}}
Basic Arithmetic with Integers
Python supports all the standard arithmetic operations you'd expect. Let's see them in action:
| Operator | Operation | Example | Result |
|---|---|---|---|
+ | Addition | 5 + 3 | 8 |
- | Subtraction | 10 - 4 | 6 |
* | Multiplication | 6 * 2 | 12 |
/ | Division | 15 / 3 | 5.0 |
// | Integer Division | 15 // 4 | 3 |
% | Modulo (Remainder) | 15 % 4 | 3 |
** | Exponentiation | 2 ** 3 | 8 |
Let's test some of these in code:
x = 20
y = 7
# Addition
result_add = x + y
print(f"Addition: {result_add}") # Output: Addition: 27
# Subtraction
result_sub = x - y
print(f"Subtraction: {result_sub}") # Output: Subtraction: 13
# Multiplication
result_mul = x * y
print(f"Multiplication: {result_mul}") # Output: Multiplication: 140
# Standard Division (results in a float!)
result_div = x / y
print(f"Standard Division: {result_div}") # Output: Standard Division: 2.8571428571428577
print(f"Type of Standard Division: {type(result_div)}") # Output: Type of Standard Division: <class 'float'>
# Integer Division (discards the fractional part)
result_int_div = x // y
print(f"Integer Division: {result_int_div}") # Output: Integer Division: 2
# Modulo (remainder)
result_mod = x % y
print(f"Modulo: {result_mod}") # Output: Modulo: 6
# Exponentiation
result_exp = 2 ** 5
print(f"Exponentiation: {result_exp}") # Output: Exponentiation: 32
Notice a critical point: standard division (/) always returns a float, even if the result is a whole number (e.g., 10 / 2 gives 5.0). If you specifically need an integer result from division, use integer division (//).
Floating-Point Numbers (float): The Decimal World
When precision beyond whole numbers is required – think prices, measurements, or scientific calculations – you'll turn to floating-point numbers.
What they are: Floating-point numbers, or "floats," are numbers that have a decimal point. They can represent fractions and real numbers. Python stores these using a double-precision 64-bit format, which provides a good balance of range and precision for most applications.
Declaring Floats: You can declare a float simply by including a decimal point in the number:
# Positive float
price = 19.99
# Negative float
wind_speed = -12.5
# Float representing a whole number (still a float!)
distance = 100.0
# Using scientific notation (e for exponent)
# 3.0 x 10^8 (speed of light approximation)
speed_of_light = 3.0e8
Let's confirm their type:
print(type(price))
print(type(speed_of_light))
This will output:
<class 'float'>
<class 'float'>
{{VISUAL: diagram: A flowchart demonstrating the process of a Python arithmetic operation involving an integer and a float, highlighting the automatic type promotion to float.}}
Basic Arithmetic with Floats
Arithmetic operations on floats behave very similarly to integers, but the results will always be floats.
a = 15.5
b = 2.0
# Addition
print(f"Addition: {a + b}") # Output: Addition: 17.5
# Subtraction
print(f"Subtraction: {a - b}") # Output: Subtraction: 13.5
# Multiplication
print(f"Multiplication: {a * b}") # Output: Multiplication: 31.0
# Division
print(f"Division: {a / b}") # Output: Division: 7.75
# Exponentiation
print(f"Exponentiation: {a ** b}") # Output: Exponentiation: 240.25
One thing to be aware of with floats is precision issues. Due to how computers store floating-point numbers internally (binary representation), some decimal numbers cannot be represented exactly, leading to tiny inaccuracies. For most everyday tasks, this isn't a concern, but it's vital for high-precision scientific or financial calculations.
print(0.1 + 0.2) # Output: 0.30000000000000004 (not exactly 0.3)
Mixed-Type Operations: The Dominance of Floats
What happens if you combine an int and a float in an arithmetic operation? Python is smart enough to handle this gracefully. It will promote the integer to a float before performing the operation, and the result will always be a float.
integer_value = 10
float_value = 3.5
# Addition
mixed_add = integer_value + float_value
print(f"Mixed Addition: {mixed_add}") # Output: Mixed Addition: 13.5
print(f"Type of Mixed Addition: {type(mixed_add)}") # Output: Type of Mixed Addition: <class 'float'>
# Multiplication
mixed_mul = integer_value * float_value
print(f"Mixed Multiplication: {mixed_mul}") # Output: Mixed Multiplication: 35.0
print(f"Type of Mixed Multiplication: {type(mixed_mul)}") # Output: Type of Mixed Multiplication: <class 'float'>
This automatic type promotion ensures that you don't lose any precision when performing operations involving both integers and floats.
{{VISUAL: photo: A calculator displaying various numbers, some integers and some with decimal points, visually representing the concepts of int and float in everyday context.}}
Summary
- Integers (
int) are whole numbers, ideal for counts, indices, and discrete values. They have arbitrary precision. - Floating-point numbers (
float) are numbers with decimal points, used for measurements, prices, and values requiring fractional precision. - Python supports standard arithmetic operations:
+,-,*,/,//,%,**. - Standard division (
/) always returns afloat. Use integer division (//) for whole number results. - When an
intand afloatare combined in an operation, theintis promoted to afloat, and the result is afloat.
You've now got a solid grasp on how to work with numbers in Python. These fundamental data types will be constants in your programming journey. Next up, we'll explore another incredibly common and versatile data type: strings!
Text: String Data
Text: String Data
Imagine a world without text. No names, no messages, no instructions, no web pages. Pretty boring, right? In Python, just like in the real world, text is everywhere, and it's incredibly important. We use text to represent user input, display information, store names, communicate messages, and much more.
In programming, a sequence of characters, such as letters, numbers, and symbols, is called a string. Python has robust and flexible ways to handle these textual data types, making them a fundamental building block for almost any application.
What are Strings?
A string is an ordered sequence of characters. Each character in a string occupies a specific position, allowing you to access and manipulate them individually or in groups. Python treats strings as objects, which means they come with a set of built-in capabilities (methods) that we'll explore in more advanced chapters. For now, let's focus on the basics.
Creating Strings
You can create a string in Python by enclosing characters within single quotes (' '), double quotes (" "), or triple quotes (''' ''' or """ """).
Single and Double Quotes
Most commonly, you'll use single or double quotes. Python doesn't have a preference; they are functionally identical. The main reason to choose one over the other is convenience when your string itself contains quotes.
# Using single quotes
my_string_1 = 'Hello, Python!'
print(my_string_1)
# Using double quotes
my_string_2 = "Welcome to the course."
print(my_string_2)
# Handling quotes within strings
message_1 = "He said, 'Python is fun!'"
print(message_1)
message_2 = 'It\'s a beautiful day.' # Using an escape character for single quote
print(message_2)
message_3 = "The book is titled \"Python for Beginners\"." # Using an escape character for double quote
print(message_3)
Notice how message_1 uses double quotes to enclose the string, allowing the single quote inside to be part of the text without issue. Conversely, message_2 uses an escape character (\) before the apostrophe to tell Python to treat it as a literal single quote, not the end of the string. We'll touch more on escape characters later.
Triple Quotes
Triple quotes are especially useful for multi-line strings or for docstrings (documentation strings) which describe functions, classes, and modules.
multi_line_string = '''
This is a string
that spans
multiple lines.
'''
print(multi_line_string)
another_multi_line = """
You can also use
triple double quotes
for the same purpose.
"""
print(another_multi_line)
Python preserves the line breaks and indentation exactly as they appear within the triple quotes.
Basic String Operations
Now that we know how to create strings, let's explore some fundamental operations you can perform on them.
1. Concatenation: Joining Strings
You can combine two or more strings together using the + operator. This process is called concatenation.
first_name = "Alice"
last_name = "Wonderland"
full_name = first_name + " " + last_name # Add a space in between
print(full_name) # Output: Alice Wonderland
greeting = "Hello"
name = "Bob"
message = greeting + ", " + name + "!"
print(message) # Output: Hello, Bob!
{{VISUAL: diagram: illustrating string concatenation with two string blocks merging into one longer string block.}}
Remember, you can only concatenate strings with other strings. Trying to concatenate a string with a number (e.g., "Age: " + 30) will result in a TypeError. If you need to include numbers, convert them to strings first using str().
2. Indexing: Accessing Individual Characters
Strings are sequences, which means each character has an associated position, or index. Python uses zero-based indexing, meaning the first character is at index 0, the second at 1, and so on.
You can access individual characters using square brackets [] with the index number.
my_word = "Python"
# Positive indexing
print(my_word[0]) # Output: P (the first character)
print(my_word[1]) # Output: y
print(my_word[5]) # Output: n (the last character)
# Negative indexing
# You can also access characters from the end of the string using negative indices.
# -1 refers to the last character, -2 to the second to last, and so on.
print(my_word[-1]) # Output: n
print(my_word[-2]) # Output: o
print(my_word[-6]) # Output: P (the first character)
If you try to access an index that is out of range (e.g., my_word[6] or my_word[-7]), Python will raise an IndexError.
3. Slicing: Extracting Substrings
While indexing lets you grab a single character, slicing allows you to extract a portion (a "slice") of a string. The syntax for slicing is [start:end:step].
start: The index where the slice begins (inclusive). If omitted, defaults to 0.end: The index where the slice ends (exclusive). If omitted, defaults to the end of the string.step: How many characters to jump after retrieving one (defaults to 1).
full_phrase = "Python Programming"
