Variables

 Variables

  • Variables are containers for storing data values.
  • Variables is a location in memory used to store some data (value).
  • In Python, variables are Dynamic (We don't even have to declare the type of the variable).

Rules in Naming a Variable

  • Rule 1: A variable name must start with a letter or the underscore character.
  • Rule 2: A variable name cannot start with a number.
  • Rule 3: A variable name can only contain alpha-numeric characters and underscores (A-Z, 0-9, and _).
  • Rule 4: A variable accepts only underscore _ symbol. (No other symbol is accepted.)
  • Rule 5: Variable names are Case Sensitive (age, Age and AGE are three different variables).
  • Rule 6: It can't accept reserve/keywords.

Example 1

      a = 9

      print(a)

Output:

      9

Example 2

      A = 2.0

      print(A)

Output:

      2.0

Example 3

      z = "Lokesh"

      print(z)

Output:

      Lokesh

Example 4

      a1 = 40

      print(a1)

Output:

      40

Example 5

      a_1 = 60

      print(a_1)

Output:

      60

Many Values to Multiple Variables

  • Python allows you to assign values to multiple variables in one line.

a, b, c = 10, 20, 30

 

print(a)

print(b)

print(c)

Output:

10

20

30

Note: Make sure the number of variables matches the number of values, or else you will get an error.

One Value to Multiple Variables

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

a = b = c = "AI"

 

print(a)

print(b)

print(c)

Output:

AI

AI

AI

Storage Location

  • In Python, objects are created based on value.
  • id() — used to get address.

Example

a = 10

id(a)

Output:

2855789685328

b = 10

id(b)

Output:

2855789685328

Delete Variable

To delete a single variable

a = 10

 

del a

After deleting the variable:

print(a)

Output:

NameError: name 'a' is not defined

To delete multiple variables at a time

a = 10

b = 20

c = 30

 

del a, b

 

Post a Comment

0 Comments