xSKILLby Infirals
Register

Python for Beginners

0 of 24 notes read 0%

Reading progress is saved to your INFIRALS account. Sign in to keep this note marked as read.

Variables and names

Basics7 min readLesson 2 of 8

A variable is a name that refers to a value. You create one with =, putting the name on the left and the value on the right. The name can then stand in for the value wherever you use it. Good names make a program easier to read months later, for you and for anyone else who opens the file.

python
name = 'Ravi'
age = 15
print(name)
print('Age:', age)

2.1 How assignment works

The right side is calculated before the left side receives the result. score = score + 1 means take the current score, add one, then store the new number under the same name. Names are case sensitive: total, Total, and TOTAL are three different names.

2.2 Naming rules

  • A name starts with a letter or an underscore.
  • Letters, digits, and underscores can follow the first character.
  • Spaces and hyphens are not allowed.
  • Keywords such as if, for, and class are reserved.
python
score = 10
score = score + 5
print(score)
label = 'level'
print(label, score)

2.3 Common mistake

Using a name before it has a value breaks the code. print(total) works only after a line like total = 0 has run. A misspelled name raises NameError when Python reaches it. Read the error for the name Python could not find and compare it with the assignment above. Reassigning a name to a different kind of value is allowed, but keep the purpose of the name clear.

python
left = 'tea'
right = 'coffee'
left, right = right, left
print(left, right)

2.4 Practice

  1. Write a small profile with name, city, and age variables.
  2. Print a sentence that uses all three.
  3. Change age on a new line and print the sentence again.

For longer variable names, use underscores, as in favourite_subject. Write constants such as MAX_SCORE in capitals to signal that the value should stay fixed.

Interview questions

3 questions from this note. Open one to see the answer; no account needed.

  • 01What does `=` do in `x = 5`?

    It evaluates the right side and binds the name `x` to that value. Use `==` when you want to compare two values.

  • 02Are `name` and `Name` the same variable?

    No. Python names are case sensitive, so `name` and `Name` refer to separate values.

  • 03What error follows `print(total)` when no `total` has been assigned?

    A `NameError` saying the name `total` is not defined. Assign `total` before printing it.