Reading history

Python Variables: Create, Name and Change Them

7 min read 1 views

Learn how Python variables work: creating them, naming rules, multiple assignment, swapping, checking types and converting values, with runnable examples.

A variable is a name you attach to a value so you can use that value again later. In Python you create one simply by assigning to it with =. There is no separate declaration step and no type keyword.

In this lesson you will learn

  • How to create a variable and change its value
  • The rules and conventions for naming variables
  • How to assign several variables in one line and swap two values
  • How to check a variable’s type with type()
  • How to convert between text and numbers
  • Why two names can point to the same object

Creating a Variable

Write a name, an equals sign and a value. Python creates the variable the moment that line runs.

student_name = "Nusrat"
roll = 17
cgpa = 3.82
is_enrolled = True

print(student_name, roll, cgpa, is_enrolled)

Output

Nusrat 17 3.82 True

Four variables, four different kinds of value: text (a string), a whole number, a decimal number and a true/false value. Python worked out each type on its own.

Think of it as a label, not a box

In C, a variable is a fixed-size box in memory that holds one type. In Python, a variable is closer to a sticky label you put on a value. The value lives somewhere in memory; the name just points at it. This idea explains several behaviours later in the lesson.

Changing a Variable

Assigning again moves the label to a new value. The new value can even be a different type.

battery = 100
print("Start:", battery)

battery = battery - 35
print("After a video call:", battery)

battery = "empty"
print("Now it holds text:", battery)

Output

Start: 100
After a video call: 65
Now it holds text: empty

The line battery = battery - 35 reads the current value (100), subtracts 35, and then points battery at the result. Switching from a number to text is allowed, but in real programs it usually makes code harder to follow, so keep one kind of value per variable.

Naming Rules and Conventions

Python enforces a few hard rules. Breaking one gives a SyntaxError.

RuleAllowedNot allowed
Start with a letter or underscorescore, _temp2nd_place
Use only letters, digits and underscorestotal_2026total-marks, my name
Names are case-sensitiveAge and age are two different names—
Cannot be a keywordclass_nameclass, for, if

Beyond the rules, the Python community follows a style guide called PEP 8. Its advice for variables:

  • Use snake_case: lowercase words joined by underscores, such as monthly_salary.
  • Use ALL_CAPS for values you intend never to change, such as VAT_RATE = 0.15. Python does not stop you from changing them; the capitals are a promise to other readers.
  • Avoid single letters except for short loop counters like i.
  • Do not reuse built-in names such as list, str or sum as variable names. Doing so hides the original function.

Assigning Several Variables at Once

Python lets you fill several names in one line, give many names the same value, or swap two values without a temporary variable.

city, river, year = "Sylhet", "Surma", 2026
print(city, river, year)

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

left, right = "tea", "coffee"
left, right = right, left
print("left:", left, "| right:", right)

Output

Sylhet Surma 2026
0 0 0
left: coffee | right: tea

The swap works because Python first builds the pair on the right side, ("coffee", "tea"), and only then unpacks it into the names on the left. In C you would need a third variable to do the same job.

Checking a Variable’s Type

The built-in type() function tells you what kind of value a name currently points to.

price = 120
weight = 2.5
item = "hilsa"
fresh = False

print(type(price))
print(type(weight))
print(type(item))
print(type(fresh))

Output

<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
TypeMeaningExample value
intWhole number of any size120, -7
floatNumber with a decimal point2.5, 3.0
strText inside quotes"hilsa"
boolEither True or FalseFalse
NoneType“No value yet”None

Unlike C, a Python int has no fixed range. It grows as large as your computer’s memory allows, so overflow is not something you need to worry about for whole numbers.

Converting Between Types

Values typed by a user, or read from a file, arrive as text. Before you can do arithmetic on them you have to convert them.

pages_read = "40"
pages_left = 60

total = int(pages_read) + pages_left
print("Total pages:", total)

summary = "I read " + str(total) + " pages today"
print(summary)

Output

Total pages: 100
I read 100 pages today

int() turns the text "40" into the number 40. Going the other way, str() turns the number back into text so it can be joined to other text with +. Without those calls Python raises a TypeError, because it refuses to guess whether you meant to add numbers or join strings.

When Two Names Share One Object

Because a variable is a label, two labels can stick to the same value. With numbers and strings you rarely notice. With a list, which can change in place, it matters.

team_a = ["Rafi", "Mim"]
team_b = team_a          # both names point to the same list

team_b.append("Tanvir")
print(team_a)
print(team_a is team_b)

Output

['Rafi', 'Mim', 'Tanvir']
True

Writing team_b = team_a did not copy the list. It attached a second label to the same list, so adding through team_b also changes what team_a shows. The is operator confirms both names point to one object. You will learn how to make a real copy in the Python Lists lesson.

Common Mistakes

  1. Using a variable before creating it. Python reads top to bottom, so print(total) on line 1 fails if total = 10 is on line 2. The error is NameError.
  2. Confusing = and ==. One equals sign assigns a value. Two equals signs compare values.
  3. Adding text and numbers. "Age: " + 21 raises a TypeError. Use str(21) or an f-string such as f"Age: {age}".
  4. Typos in names. totl and total are two different variables. A typo on the left side silently creates a new one.
  5. Shadowing built-ins. After sum = 5, calling sum([1, 2]) fails because sum is no longer the function.

Best Practices

  • Choose names that explain the value: delivery_charge beats dc.
  • Keep one kind of value per variable throughout its life.
  • Group related constants at the top of the file in ALL_CAPS.
  • Convert input to the right type as soon as you read it, so the rest of the program works with clean values.

Practice Exercises

Exercise 1. Create variables for a book’s title, its page count and its price, then print all three on one line.

Show answer
title = "Learning Python"
pages = 320
price = 450.0
print(title, pages, price)

Exercise 2. Which of these names are valid? my_score, 3rd_try, _hidden, user-name, while

Show answer

Valid: my_score and _hidden. Invalid: 3rd_try starts with a digit, user-name contains a hyphen, and while is a keyword.

Exercise 3. Swap the values of a = 5 and b = 9 in a single line, then print them.

Show answer
a, b = 5, 9
a, b = b, a
print(a, b)   # 9 5

Exercise 4. qty = "3" and unit_price = 25. Print the total cost as a number.

Show answer
qty = "3"
unit_price = 25
print(int(qty) * unit_price)   # 75

Frequently Asked Questions

Do I need to declare a variable’s type in Python?

No. Python reads the type from the value you assign. You can add optional type hints such as age: int = 20, but Python does not enforce them at run time.

Does Python have constants?

Not built into the language. By convention, a name written in ALL_CAPS tells other programmers the value should not change.

What is the difference between is and ==?

== checks whether two values are equal. is checks whether two names point to the very same object in memory.

How do I delete a variable?

Use del name. The name disappears, and using it afterwards raises a NameError.

Summary

  • Create a variable by assigning to it: name = value.
  • Names start with a letter or underscore and use snake_case by convention.
  • One line can assign several variables or swap two of them.
  • type() shows a value’s type; int(), float() and str() convert between types.
  • A variable is a label for an object, so two names can share one object.
Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *