2.2. Variables#

Variables are containers for storing data values. They are essential for any computation or manipulation of data. Variables can store different types of data, including numbers, text, and more complex structures.

2.2.1. Variable Naming Rules:#

  • Names can contain letters, digits, and underscores.

  • They must start with a letter or an underscore, not a digit.

  • They are case-sensitive (age is different from Age).

  • Reserved keywords (e.g., for, if, else) cannot be used as variable names, as they inherently have special meanings in Python

my_variable = 10  # valid
_variable2 = "Hello"  # valid

x = 5:

  • We are creating a variable called x and assigning the value 5 to it. Python now knows that whenever you refer tox, you mean the number 5.

  • 5 is an integer data type (int).

y = "Python":

  • Here, we create another variable y and assign it the string “Python”

  • The variable is now set to the text “Python”.

1variable = 5  # invalid
  Cell In[4], line 1
    1variable = 5  # invalid
    ^
SyntaxError: invalid decimal literal

Remember, variable names cannot start with digits!

2.2.2. Assigning Values:#

  • Assignment is done using the = operator.

  • You can assign multiple variables in one line.

x = 5
y = "Python"
a, b = 10, "Data Science"

a, b = 10, "Data Science":

  • This is a way to assign multiple variables at once.

  • a is assigned the value 10 (an integer).

  • b is assigned the value “Data Science” (a string).

  • Python uses the comma to separate values and variables, and each value gets assigned to the corresponding variable in order.

For the last line, a would be set to the value of 10, and b would be set to the string of “Data Science”

print(a)
print(b)
10
Data Science

2.2.3. Changing Types:#

  • Python allows reassigning variables to different types on the fly.

var = 10       # Integer
var = "hello"  # String

var = 10:

  • We first assign the integer 10 to the variable var.

  • Python associates var with this numeric value.

var = "hello":

  • We then reassign var to the string "hello".

  • Python now “forgets” that var was an integer and treats it as a string. This flexibility is because Python is considered “dynamically typed”, meaning variables don’t have fixed types. They can change when needed!