Python Variables

A variable is like a container which is used to store a value. At times there is a need to store some data for future usage. A variable in python needs not to be declared before usage, it is created the moment you assign it a value.

For example-

a = 10
b = 'cat'

The print statement

To output the value contained by a variable, we use the print statement.

a = 10
b = 'cat'
print(a)
print(b)

Output

10

cat

The type statement

If you want to check the type of a variable, you can use the type statement.

For example-

a = 10
b = 'cat'
print(type(a))
print(type(b))

Output

<class 'int'>

<class 'str'> 

This means the first variable is of integer type and variable named b is of string type.

In python, variables do not need to be declared with a particular data type. Even the type of a variable can be changed at any moment.

For example-

a = 7 # a is of type int
a = 'car' # a is now of str type.

Note: Like other programming languages like C, C++ or Java, the value of a variable can be overwritten at any moment.

str variables can be declared by using either single or double quotes.

username = 'aman'
#or
username = "aman"

Naming Conventions

A variable can have a single character as name or even a word (for example- car, usernmae, age). There are some rules to create variables in python.

  • A variable name cannot start with a number but can end with a number.
  • A variable name must start with underscore(_) or a letter.
  • Variable names in python are case sensitive (For example car and CAR are two different variables and not the same).
  • A variable name can contain numbers(but not at the start), alphabets (a-z, A-Z) and underscores.

Some valid variable names

age = 21
username = 'pradeep'
_address = 'sagar'
myAddress = 'bhopal'
ROLLNO = 1001
user1 = 'derek'

Some invalid variable names

1user = 'derek' #A variable name cannot contain start with a number.

my-Address = 'bhopal' #A variable name cannot contain dashes(-).

my Address = 'bhopal' #A variable name cannot contain spaces.

Assignment

You can assign values to different variables separetely or in the same line.

Assigning values to variables separately-

a = 1
b = 4
c = 7
print(a)
print(b)
print(c)

Assigning values to different variables in the same line-

a, b, c = 1, 4, 7
print(a)
print(b)
print(c)

The output in either case will be-

1

4

7