Python - Variables

Python - Variables


Previous Page

Variable is a given name to a reserved memory location. When a variable is created in the program, it reserves some space in the memory to store value(s) and the interpreter allocates memory for the given variable based on its datatype. Value(s) is stored in the variable by assigning different datatypes to it like number, string and sequences, etc.

Assigning Value to a Variable

Unlike Java & C++, Python does not require to declare a variable or its data type. The data type of a variable is set when a value is assigned to it. To assign a value(s) to the variable, = operator is used.

#store number in the variable 'x'
x = 15
print(x)

#store text in the variable 'y'
y = 'Hello'
print(y)

#store sequence in the variable 'z'
z = [1, 2, 3]
print(z)

Output

15

Hello

[1, 2, 3]

In Python, when a new value is assigned to the variable, the old value and its datatype will be overwritten by new value and its datatype.

#variable 'x' holds integer datatype with value 15
x = 15

#Now, variable 'x' holds string datatype with value 'Hello'
x = 'Hello'
print(x)

Output

Hello

Assign Value to Multiple Variables

In Python, multiple variables can be assigned value(s) in a single line. Please see example below.

x , y = 15, 20.5
print(x)
print(y)

x, y = [1, 2, 3], ('red', 'blue', 'green')
print(x)
print(y)

Output

15
20.5

[1, 2, 3]
('red', 'blue', 'green')

Print Variable

The Python print() built-in function is used to print variables on the screen, or other standard output device. To combine string value of two or more variable inside print() function, comma (,) operator is used which concatenates string values of variables with a whitespace.

MyString = "John"
MyNumber = 25
print(MyString, "is", MyNumber, "years old.")

x = 50
y = 30
print(x, y)

Output

John is 25 years old.

50 30

Alternatively, it can also be achieved with + character but with some limitation. It combines two or more variables of same datatypes. With string datatype, it returns concatenated variables and with number datatypes it returns sum of the variables. With mixed datatypes, it will raise an exception.

MyString = "John"
MyLocation = "London."
print(MyString + " Lives in " + MyLocation)

x = 25
y = 10
print(x + y)

#Mixing datatypes will raise an exception
print(MyString + "is" + x + "years old.")

Output

John Lives in London.

35

TypeError: Can't convert 'int' object to str implicitly

It is possible to use , and + characters inside print() function at the same time to get the desired result.

x = 25
y = 10
print("sum of",x,"and",y,"is",x+y)

Output

sum of 25 and 10 is 35

Variable Name

There are some reserved keywords in Python which cannot be used as variable name. Along with this, rules for creating Python variable name are listed below:

  • It must start with a letter or the underscore character
  • It cannot start with a number.
  • It can only contains alpha-numeric characters and underscores (A-Z, a-z, 0-9, and _ ).

Please note that Python is a case-sensitive language. Hence, variables in Python are also case-sensitive.

Global Variable

If a variable is created outside a function, it is called global variable. A global variable can be used anywhere, inside the function and outside the function.

Example

In the below example, a global variable called MyString is created and used inside the function called MyPrint() to print the global variable.

MyString = "Hello World!."
def MyPrint():
  print(MyString)

MyPrint()

Output

Hello World!.

If a variable with same name is created inside the function, it will be a local variable and can be used inside the function only. Any operation performed on local variable will not change the global variable.

Example

In the below example, a global variable called MyString is created in the main body of the program. A local variable with the same name is also created inside the function called MyPrint(). This local variable can only be used inside the function MyPrint(), therefore the function uses the local variable when it is called in the program. Along with this, any operation performed on the local variable will not change the global variable, therefore when the variable MyString in printed outside the function, the variable takes global value only which is unaffected by the local variable.

MyString = "Hello World!."
def MyPrint():
  MyString = "Hello Python"
  print(MyString)

MyPrint()
print(MyString)

Output

Hello Python

Hello World!.

Python global keyword

In Python, a variable created inside a function is a local variable and can only be used inside that function. To create a global variable inside a function, Python global keyword is used. A global variable can be used anywhere, inside the function and outside the function.

Example

In the below example, the global keyword is used to create a global variable called MyString inside the function called MyFunction.

def MyFunction():
  global MyString
  MyString = "Python"

MyFunction()
print("Learning", MyString ,"is fun.")

Output

Learning Python is fun.

Example

The value of a global variable, which is created outside of a function, can be changed inside the function by referring to the variable using the global keyword.

MyString = "Java"

def MyFunction():
  global MyString
  MyString = "Python"

MyFunction()
print("Learning", MyString ,"is fun.")

Output

Learning Python is fun.

Previous Page