Python Variables
Python Variables

Python Variables

A Python variable is a name given to a memory location. It is a reference to a Python object. Once we assign an object to a variable, we can refer to the object using that variable name. In simpler words, Python variables as the name given to the containers that store data, where a container refers to an object.

How to create Python variables?

In most programming languages we need to declare and define variables in advance before we can use them. In Python, we don’t need to declare or define variables in advance. To create a variable, we just assign it a value using the assignment operator (=). Therefore, the variable is created at the moment we first assign a value to it. For example,

# creating variables
name = "Sheldon"
rollno = 121
marks = 99.67

# printing variable values
print(name)
print(rollno)
print(marks)

Output:

Sheldon
121  
99.67

The naming of Python variables

As we already discussed that a variable is a name given to a memory location. We can give it a name as per our choice. However, there are certain rules and naming conventions for Python variables. We need to follow the following rules while naming a variable:

  • A variable name can only contain alpha-numeric characters (A-Z, a-z, 0-9) and underscore (_).
  • It must not contain any special characters (@, #, !, $, etc.).
  • A variable name can only start with an alphabet (lowercase or uppercase) and underscore character.
  • It cannot start with a digit (0-9).
  • Variable names are case-sensitive.
  • A variable name must not be a keyword (reserved words) of the programming language.

Example of some proper variable names,

myvariable, value, var123, mylist, My_variable, myvar2

Apart from this, we can have multi-word variable names. But variable names with more than one word are difficult to read. There are some methods that we can use for constructing multi-word variable names, making them more readable.

Camel Case

According to this method, the first letters of second and subsequent words are capitalized. In other words, we write each word except the first one starting with a capital letter. For example, we can define a variable and assign a python string to it as follows.

nameOfCar = "Tesla"

Pascal Case

According to this method, each word should start with a capital (or uppercase) letter. For example,

NameOfCar = "Tesla"

Snake Case

According to this method, each word is separated by an underscore character. For example,

name_of_car = "Tesla"

How to determine the data type of Python variables?

Data types in Python are the classification or categorization of data items that represent the kind of value we store in a variable. We can determine the data type of a Python variable using the type() method as shown in the example below.

# creating variables
name = "Sheldon"
rollno = 121
marks = 99.67

# printing variable type
print(type(name))
print(type(rollno))
print(type(marks))

Output:

<class 'str'>
<class 'int'>
<class 'float'>

Assigning values to Python variables

As we have already discussed, a variable is created as soon as we assign a value to it. But that value is not the final value of the variable. We can reassign a new value again as per our requirement. In addition, the data type of a variable doesn’t need to remain the same. We can change it according to the value assigned. For example,

# defining variable with an integer value
myvar = 2021

print("initial value of myvar:")
print(type(myvar), myvar)

# reassigning new value to myvar
myvar = "Jack"

print("new value of myvar:")
print(type(myvar), myvar)

Output:

initial value of myvar:
<class 'int'> 2021
new value of myvar:
<class 'str'> Jack

Assigning a single value to multiple variables

In Python, we can assign the a single value to multiple variables. For this, we need to simultaneously use the assignment operator (=) with all variables. For example,

# assigning same value to three variables
a = b = c = 1000

# printing values of all variables
print("a =", a)
print("b =", b)
print("c =", c)

Output:

a = 1000
b = 1000
c = 1000

Assigning different values to multiple variables

In Python, we can assign values to multiple variables simultaneously. For this, we need to use comma (,) separated values and variable names. Here, we need to ensure that number of variables on the left-hand side must be equal to the number of values on the right-hand side, or else we will get an error. For example,

# assigning different values to multiple variables
a, b, c = 'apple', 'banana', 'cherry'

# printing values of variables
print("a =", a)
print("b =", b)
print("c =", c)

Output:

a = apple
b = banana
c = cherry

What is Casting?

Casting is the method to convert the variable of one data type to another data type. To be more specific we call it Type Casting. Type casting may be Implicit or Explicit. In Implicit type casting Python converts data type into another data type automatically. In Explicit type casting, we need to specify the data type of the variable. Casting can be done using the following type functions:

int() – it constructs an integer number from an integer value, a float value(removing decimals), or a string. Here the string must represent a whole number. For example,

# using int() function for different types
int_from_int = int(20)
int_from_float = int(14.50)
int_from_str = int('8')

# printing types and values
print(type(int_from_int), int_from_int)
print(type(int_from_float), int_from_float)
print(type(int_from_str), int_from_str)

Output:

<class 'int'> 20
<class 'int'> 14
<class 'int'> 8

float() – it constructs a float number from an integer value, a float value, or a string. Here also a string must represent a float or an integer value. For example,

# using float() function for different types
float_from_int = float(20)
float_from_float = float(14.50)
float_from_str = float('8.65')

# printing types and values
print(type(float_from_int), float_from_int)
print(type(float_from_float), float_from_float)
print(type(float_from_str), float_from_str)

Output:

<class 'float'> 20.0
<class 'float'> 14.5
<class 'float'> 8.65

str() – it constructs a string from an integer value, a float value, or a string. For example,

# using str() function for different types
str_from_int = str(20)
str_from_float = str(14.50)
str_from_str = str('8.65')

# printing types and values
print(type(str_from_int), str_from_int)
print(type(str_from_float), str_from_float)
print(type(str_from_str), str_from_str)

Output:

<class 'str'> 20
<class 'str'> 14.5
<class 'str'> 8.65

What are Global variables in Python?

Global variables are the variables that we define outside a function in python. We can use these variables anywhere within the program.

Whereas the variables that we define inside a function are said to be Local variables. We can use these variables inside the function definition only. We cannot access these variables outside the function.

Let’s see an example below.

# global variable
gvar = 2021

def func():
    # local variable
    lvar = 2020
    print("Global variable inside function:", gvar)
    print("Local variable inside function:", lvar)

func() # calling function
print("Global variable outside function:", gvar)
try:
    print("Local variable outside function:", lvar)
except Exception as e:
    print("Error:", e)

Output:

Global variable inside function: 2021
Local variable inside function: 2020
Global variable outside function: 2021
Error: name 'lvar' is not defined

Here, we can see that when we tried to access local variable lvar, it gave an error. This is because we cannot access a local variable outside the function.

The global keyword

As we discussed, whenever we define a variable inside a function it is a Local variable. However, we can create a global variable inside the function using the global keyword. If we use global keyword before a variable name, the scope of that variable changes to global so that it can be accessed anywhere. For example,

# function definition
def func():
    # using global keyword to define global variable inside function
    global var
    var = 99.99

func() # calling function
# value of variable that was defined inside the function
print("Value of Variable defined with global keyword:", var)

Output:

Value of Variable defined with global keyword: 99.99

In addition, we can also use global keyword to modify a global variable inside a function. For example,

# global variable
fruit = "mango"

def func():
    # modifying variable using global keyword
    global fruit
    fruit = "apple"

print("Value of fruit before calling function:", fruit)
func() # calling function
print("Value of fruit after calling function:", fruit)

Output:

Value of fruit before calling function: mango
Value of fruit after calling function: apple

Conclusion

In this article, we have discussed about Python variables. We have discussed how to create variables, name them, determine their data type, and assign values to them. We have also read about the concept of Casting and Global Variables in Python.

Piyush Sharma

Third-year computer engineering student inclined towards the latest trends and technology. Always keen to explore and ready to learn new things. To read more articles on Python, stay tuned to avidpython.com.

Leave a Reply