Lesson 3 of 5 · Variables · 2 min read · Updated
Naming variables
Python has simple rules for variable names. Learn the rules and how to choose a good name.
Understand
You choose the name of a variable. Python only asks that the name follows a few rules.
A good name also tells the reader what the variable holds.
The rules for a name
- Use letters, digits and the underscore
_. - Do not start with a digit.
- Do not use spaces. Write
first_name, notfirst name. - Small and capital letters are different.
nameandNameare two different names. - Do not use a word that Python keeps for itself. These are called keywords.
Use it
These two names follow every rule.
student_name = "Asha"
marks2 = 90
print(student_name)
print(marks2)
Asha
90
The underscore joins the two words. The digit 2 is fine because it is not the first character. Names like student_name and marks2 say what they hold.
Practice
This code gives an error. Run it, read the last line, and fix it so it prints Asha.
To try it, copy the code into a file on your computer and run it. Your output should match the expected output below.
Expected output
Asha
Need a hint?
- The two names must be spelled exactly the same, including capital letters.
- Write
print(name)with a small n.
Show a solution
name = "Asha"
print(name)
This code gives an error because a name has a space. Fix it so it prints Asha.
To try it, copy the code into a file on your computer and run it. Your output should match the expected output below.
Expected output
Asha
Need a hint?
- Replace the space with an underscore.
- Use
first_namein both lines.
Show a solution
first_name = "Asha"
print(first_name)
This name starts with a digit. Rename it so the code prints Ravi.
To try it, copy the code into a file on your computer and run it. Your output should match the expected output below.
Expected output
Ravi
Need a hint?
- A name cannot start with a digit.
- Use a name like
second_placein both lines.
Show a solution
second_place = "Ravi"
print(second_place)
Which is a valid variable name?
Why it works
Python treats name and Name as two different names. Here only name exists, so Python cannot find Name.
name = "Asha"
print(Name)
NameError: name 'Name' is not defined. Did you mean: 'name'?
Keywords are words with a special meaning in Python, so you cannot use them as variable names. You will meet them one by one as you learn.
Create a free account to save your progress, or sign in.