• Python Basics

  • Python Variables

  • Operators in Python

  • Conditional Statements in Python

  • Python Lists

  • Python Tuples

  • Python Sets

  • Python Dictionaries

  • Loops in Python

  • Python Arrays and Functions

  • Conclusion

Python Variable Names

Variable Names in Python

When naming your variables, you need to follow a few rules:

  1. A variable name must start with a letter or the underscore (_) character.
  2. It cannot start with a number.
  3. Variable names can only contain letters, numbers, and underscores (A-z, 0-9, and _).
  4. Variable names are case-sensitive (age, Age, and AGE are different variables).

Legal variable names:

python
1myvar = "Smith"
2_my_var = "Smith"
3myVar2 = "Smith"

Illegal variable names:

python
12myvar = "Smith"  # Cannot start with a number
2my-var = "Smith"  # Hyphens are not allowed
3my var = "Smith"  # Spaces are not allowed

Python Case Sensitive

Variable names in Python are case-sensitive. This means that myVar, MyVar, and myvar are all different variables.

Example:

python
1a = 4
2A = "Sally"
3# Here, a and A are two different variables

Python Multi-Word Variable Names

If your variable name has more than one word, there are a few common styles for writing it:

  • Camel Case: Each word except the first starts with a capital letter.
python
1myVariableName = "Smith"
  • Pascal Case: Every word starts with a capital letter.
python
1MyVariableName = "Smith"
  • Snake Case: Each word is separated by an underscore.
python
1my_variable_name = "Smith"

Assigning Multiple Values to Variables

Python allows you to assign values to multiple variables at once.

Example:

python
1x, y, z = "Orange", "Grapes", "Cherry"
2print(x)
3print(y)
4print(z)

Assigning One Value to Multiple Variables

You can assign the same value to multiple variables in one line.

Example:

python
1x = y = z = "Orange"
2print(x)
3print(y)
4print(z)

Unpacking a Collection

If you have a collection (like a list or tuple), you can unpack its values into variables.

Example:

python
1fruits = ["Orange", "Grapes", "Cherry"]
2x, y, z = fruits
3print(x)
4print(y)
5print(z)

Frequently Asked Questions