【Python Super Primer】The First Step in Programming! What are 'Variables'? A Gentle Explanation of How to Use Them and Naming Rules #3

Welcome back to your Python learning adventure! In our last session, we had some fun making Python act like a super-smart calculator. That's a great start! But what if we want to remember a number or a piece of text to use it later, or maybe use it multiple times without typing it over and over? That's where "variables" come in – they are one of the most fundamental building blocks in programming!

Don't let the name scare you; the concept is actually very simple. Think of variables as labeled boxes where you can store information. In this post, we'll gently explore what variables are, why they're so useful, how to create and use them in Python, and the important rules for naming them.

Ready to take your first *real* step into programming logic? Let's learn about variables!


What is a Variable? (Imagine a Labeled Box!)

Imagine you have a collection of empty boxes. You can put something inside a box (like a number, or a piece of text) and then you stick a label on it. This label is the variable name, and the item inside is the value it stores.

For example:

  • You could have a box labeled my_age and put the number 30 inside it.
  • Another box could be labeled user_greeting and contain the text "Hello there!".

In programming, a variable is essentially a named storage location in your computer's memory where you can keep a piece of data. By using the variable's name (the label), you can easily access or change the data (the item in the box) whenever you need to.


Why Do We Need Variables?

Variables are incredibly useful for several reasons:

  • Storing Information: This is their main job! They hold onto data that your program needs to work with.
  • Reusability: If you have a piece of information you need to use many times in your program, you can store it in a variable and just use the variable's name. This saves you from typing the same value repeatedly and makes it easier to update if it changes.
  • Readability: Using well-named variables makes your code much easier to understand. For example, seeing total_price = item_price + tax is much clearer than just seeing 110.0 = 100.0 + 10.0. It tells a story!
  • Flexibility: The values stored in variables can change as your program runs. This allows your programs to be dynamic and respond to different situations.

Creating and Using Variables in Python

Creating (often called "declaring" or "assigning") a variable in Python is super easy. You use the equals sign (=), which is known as the assignment operator.

Important: In programming, = doesn't mean "equals" in the mathematical sense (like "is this equal to that?"). Instead, it means "assign the value on the right side to the variable name on the left side." Think of it as "put this into the box."

Creating Variables (Assignment)

Let's open Python's interactive mode (type python or py in your command line) and try it:

>>> my_number = 10
>>> user_name = "Alice"
>>> message = "Welcome to Python!"

In these examples:

  • We created a variable named my_number and stored the integer value 10 in it.
  • We created user_name and stored the text (string) value "Alice".
  • We created message and stored the string "Welcome to Python!".

Notice that when you assign a variable, Python doesn't print anything back. It just does the assignment quietly.

Using Variables

Once you've stored a value in a variable, you can use the variable's name to access that value.

One common way is to print it using the print() function:

>>> print(my_number)
10
>>> print(user_name)
Alice
>>> print(message)
Welcome to Python!

You can also use variables in calculations, just like you used numbers directly in the previous lesson:

>>> apples = 5
>>> price_per_apple = 0.75 # Storing a floating-point number
>>> total_cost = apples * price_per_apple
>>> print(total_cost)
3.75

See how much clearer that is? We can easily understand what apples * price_per_apple means!

Variables Can Hold Different Types of Data

As you've seen, variables can hold different kinds of information:

  • Numbers: These can be whole numbers (integers) like 10, -5, or 12345, or numbers with decimal points (floating-point numbers or floats) like 3.14, 0.75, or -2.5.
    >>> age = 30
    >>> pi_value = 3.14159
  • Text (Strings): Sequences of characters, like a name, a sentence, or even a single letter. In Python, you create strings by enclosing the text in either single quotes ('...') or double quotes ("..."). Both work the same!
    >>> city = "Tokyo"
    >>> country = 'Japan'
    >>> greeting = "Hello, how are you?"

Python automatically figures out the "type" of data you store in a variable. We'll talk more about data types in a future lesson!


The All-Important Variable Naming Rules (and Good Habits!)

Python has some specific rules for naming your variables. It also has some widely followed conventions (good habits) that make your code easier for you and others to read.

Must-Follow Rules (Python will give an error if you break these!):

  1. Variable names must start with a letter (a-z, A-Z) or an underscore (_). They cannot start with a number.
  2. The rest of the name can only contain letters (a-z, A-Z), numbers (0-9), and underscores (_). No spaces or special characters like !, @, #, $, %, -, +, etc.
  3. Variable names are case-sensitive. This means myVariable, myvariable, and MYVARIABLE are all different variables to Python.
  4. You cannot use Python's "keywords" as variable names. Keywords are reserved words that have special meaning in Python (e.g., if, for, while, def, class, print - although `print` is a function, it's best not to name variables like built-in functions either).

    (Don't worry about memorizing all keywords now; Python will tell you if you try to use one improperly.)

Good Habits (Conventions for Readability):

  • Use descriptive names: Choose names that clearly indicate what the variable is storing. For example, user_name is much better than un or x.
  • Use lowercase letters: The common convention in Python for variable names is to use all lowercase letters.
  • Separate words with underscores (snake_case): If your variable name consists of multiple words, separate them with underscores. This style is called "snake_case." For example: first_name, item_count, total_amount_due.

Examples of Good and Bad Names:

Good Names:

  • name
  • age
  • user_score
  • _temporary_value (starting with an underscore is often used for special cases, but it's valid)
  • product1

Bad Names (and why):

  • 1st_place (Cannot start with a number)
  • user-name (Cannot contain hyphens)
  • item count (Cannot contain spaces)
  • for (This is a Python keyword)
  • MyVariable (While valid, it doesn't follow the lowercase snake_case convention, which is preferred for readability in most Python code)

Getting into good naming habits early will make your programming journey much smoother!


Variables Can Change! (Reassignment)

The value stored in a variable isn't set in stone. You can change it or "reassign" a new value to an existing variable at any time.

>>> current_score = 100
>>> print(current_score)
100

>>> # Player scores more points!
>>> current_score = 150  # Reassigning a new value
>>> print(current_score)
150

>>> # Player gets a bonus
>>> current_score = current_score + 25 # Using the variable's own value to update it
>>> print(current_score)
175

In the last example, current_score = current_score + 25, Python first takes the current value of current_score (which is 150), adds 25 to it (making 175), and then stores this new result back into the current_score variable.


You're Now a Variable Virtuoso (Almost!)

Fantastic work! You've just learned about variables, one of the most essential concepts in programming:

  • Variables are like labeled boxes for storing data.
  • They make code reusable, readable, and flexible.
  • You create them using the assignment operator (=).
  • It's crucial to follow Python's naming rules and adopt good naming conventions (like lowercase snake_case).
  • The values in variables can be changed (reassigned).

Practice creating some variables of your own. Give them different names (following the rules, of course!) and store various numbers and pieces of text. Use them in print() statements and simple calculations. The more you use them, the more comfortable you'll become!

In our next lesson, we might dive a bit deeper into different types of data variables can hold, or perhaps explore how to get input from a user! Stay tuned!

Next #4

Post Index


コメント

このブログの人気の投稿

Post Index

【Introduction to Python Standard Library Part 3】The Standard for Data Exchange! Handle JSON Freely with the json Module #13

Your First Step into Python: A Beginner-Friendly Installation Guide for Windows #0