Chapter 7: Naming variables

How can I name my variables?

face Josiah Wang

A variable name in Python:

  • Can consist of letters, digits, or underscores (_)
  • Must start with a letter or an underscore
  • Cannot be a reserved keyword (e.g. True or while)

Variable names are also case-sensitive, so myvar is not the same as MyVar or MYVAR

>>> university = "Imperial"
>>> University = "College"
>>> UNIVERSITY = "London"
>>> print(university)
>>> print(University)
>>> print(UNIVERSITY)

Can you figure out which variable names below are valid? Test them out to confirm. Also, what error message will you receive (if any)?

1 2 3 4 5 6 7 8 9

Question 1

Is this valid?

my_variable123 = 2

Yes

Question 2

Is this valid?

_12is_thisvalid = 2

Yes

Question 3

Is this valid?

123abc = 2

No
Explanation:

Try to figure out why! What is the error given by Python?

Question 4

Is this valid?

True = 2

No
Explanation:

Try to figure out why! What is the error given by Python? Does the error message make sense?

Question 5

Is this valid?

try = 2

No
Explanation:

Try to figure out why! What is the error given by Python?

Question 6

Is this valid?

int = 2

Yes
Explanation:

This is surprisingly valid. int is not a Python keyword, although it is a built-in data type. So it can technically be used as a variable name (but please do not use it or you will confuse yourself!)

Question 7

Is this valid?

__twounderscores = 2

Yes
Explanation:

It ticks all the boxes! In fact, double underscores are often used in Python for special purposes. You will see such cases much later in the course! So do not use underscores for now.

Question 8

Is this valid?

1 = 2

No
Explanation:

A variable cannot start with a digit (let alone BE an integer)!

Question 9

Is this valid?

lambda_ = 2

Yes
Explanation:

The word lambda is a keyword (we will explore this keyword much later in the course). Some people like to add an underscore to reserved words so that it can be used as a variable, so lambda_ can be used if you absolutely must name a variable as lambda (e.g. it might be part of a common Mathematical equation).