Kahibaro
Discord Login Register

Creating variables

In Python, creating a variable is as simple as writing a name, an equals sign, and a value.

This chapter focuses on:

(What a variable is and what types of values exist are covered in other sections of this chapter.)

Basic variable assignment

The simplest way to create a variable is:

name = "Alice"
age = 20
pi = 3.14
is_student = True

This is called assignment. The general pattern is:

$$\text{variable_name} = \text{value}$$

Python reads this as “store this value in this variable.”

You do not have to say the type (int, str, etc.) when creating a variable in Python. Python figures it out from the value.

Variables are created when you assign

In Python, a variable comes into existence the first time you assign a value to it.

x = 10      # x is created here
message = "Hello"  # message is created here

If you try to use a variable before giving it a value, you’ll get an error:

print(score)   # ERROR: score is not defined
score = 100

So always assign a value before using a variable.

Re-assigning variables

You can change the value stored in a variable by assigning to it again.

counter = 0
print(counter)   # 0
counter = 5
print(counter)   # 5
counter = counter + 1
print(counter)   # 6

Python variables are like labels you can move to point at different values.

Variable names: rules

Python has some strict rules about what counts as a valid variable name.

A variable name:

Valid variable names

x
age
user_name
total3
_pi_value

Invalid variable names (and why)

3dogs      # starts with a digit
user-name  # contains a hyphen
first name # contains a space
for        # 'for' is a Python keyword

If you use an invalid name, Python will raise a syntax error when you run the code.

Python keywords (names you cannot use)

Some words are reserved by Python and have special meaning in the language. You cannot use them as variable names.

Examples (not full list):

False, True, None,
and, or, not,
if, elif, else,
for, while,
break, continue,
def, return,
class, try, except

Trying to use one of these as a variable name will cause an error:

if = 10       # ERROR: invalid syntax

You don’t need to memorize all of them right away; you’ll recognize most as you learn the language. Just remember: if Python complains about a name, it might be a keyword.

Naming style: `snake_case`

Python has a common style for writing variable names called snake_case:

Examples:

user_name
total_price
max_speed
number_of_items

While Python allows userName or UserName, the recommended style for variables is:

Following this style makes your code easier for others (and your future self) to read.

Good vs bad variable names

Python doesn’t care what your variable is called, as long as it follows the rules. But you should care, because clear names make your code easier to understand.

Clear, descriptive names

age = 25
temperature_celsius = 18.5
user_first_name = "Maria"
items_in_cart = 4

These names describe what the values represent.

Unclear names

a = 25
x1 = 18.5
s = "Maria"
n = 4

These follow the rules but do not tell you what they mean.

As a beginner, prefer longer, descriptive names over short, cryptic ones.

Case sensitivity

Python variable names are case-sensitive:

age = 20
Age = 30
AGE = 40
print(age)  # 20
print(Age)  # 30
print(AGE)  # 40

These are three different variables.

To avoid confusion:

Assigning multiple variables

Sometimes you can assign multiple variables in a single line.

Multiple assignment (same value)

x = y = z = 0
print(x, y, z)   # 0 0 0

All three variables get the value 0.

Multiple assignment (different values)

x, y, z = 1, 2, 3
print(x)   # 1
print(y)   # 2
print(z)   # 3

Python matches them position by position:

The number of variables on the left must match the number of values on the right, or Python will show an error.

Updating a variable using its current value

You will often create a variable, then update it based on its current value.

count = 0
count = count + 1   # add 1
count = count + 2   # add 2
print(count)        # 3

This pattern is extremely common in programming.

Python also provides shorter forms (like count += 1), which you will see later in the course when learning about operations.

Temporary variables

Sometimes you create a variable just to hold a value “in between” steps.

a = 5
b = 10
temp = a   # save a's value
a = b      # now a becomes 10
b = temp   # b becomes the old a (5)
print(a, b)  # 10 5

Here, temp is a temporary variable used to help swap values. Even if a variable is only used for a short time, giving it a clear name can make your code easier to follow.

Practical examples

Example 1: Simple profile

first_name = "Lena"
last_name = "Kim"
age = 19
is_student = True

Each variable name clearly describes the kind of information it stores.

Example 2: Shopping cart

item_name = "Book"
item_price = 12.99
item_quantity = 3
total_cost = item_price * item_quantity

Notice how the variable names express their meaning directly.

Summary

In the next sections, you’ll explore the different kinds of values (data types) you can store in these variables and how to work with them.

Views: 14

Comments

Please login to add a comment.

Don't have an account? Register now!