×

Python Variables

Variables are one of the most important terms we should be familiar with if we want to be good programmers. In simpler words, we use variables to store a value. We can think of variables as a name given to a container that is used to store a value, and they can be changed anytime during the execution of the program.

The syntax for creating variables in Python

Variable_name = value

Rules of Creating Variable

  • A variable name can only contain alpha-numeric characters (A-z, 0-9) and underscore ( _ ).
  • We cannot start a variable name with a number. For example, 12a is an invalid variable.
  • A variable name can start with an underscore. For example, _x is a valid variable.
  • A variable name can start with a letter. For example, age can be a variable name.
  • We can’t use keywords as variable names.

Valid Variable Names

  • first_var
  • firstvar
  • _first_var
  • firstVar
  • FIRSTVAR

Invalid Variable Names

  • 1stvar
  • first-var
  • first var

Type of Variable Names

  1. Camel Case: Except for the first word, each word starts with a capital letter in Camel Case.
    For example, myAge.
  2. Pascal Case: Each word of the variable name starts with a capital letter in Pascal Case.
    For example,  MyAge.
  3. Snake Case: Each word of the variable name is separated by an underscore in a Snake case.
    For example, my_age.

Variable Declaration

A variable can be created the moment you assign a value to it. Python doesn’t have any particular command to create a variable.

We don’t have to declare a variable in python before using it. Python is not statically typed, so we don’t have to declare the data type before using any variable. We can assign a value with the ‘=’ operator and start using it. But we can change its data type after they have been set in a code.

Let’s understand with example:

#declaring the variables
a = 9                                                         #a is of type integer
b = 10.5                                                    #b is of type float
c = “TutorialAndExample”                     #c is of type string


#displaying the variables
print(a)
print(b)
print(c)

Output:

9
10.5
TutorialAndExample

Re-declaration of Variables:

Variables can be re-declared any number of times in a program. It doesn’t affect the program but the memory location where the value is stored.

Let’s understand with an example.

#declare the variable
a =  20
# re-declare the variable a
a =  40


#display the variable
print(a)

Output:

40

Explanation:

In this code, a is first assigned a value of 20, but later, it gets re-assigned with a value of 40. Now, if we print, the value of it will be 40, not 20.

Assigning One Value to Multiple Variables:

We can assign one value to more than one variable simultaneously. For that, we use the ‘=’ operator.

Let’s understand with an example.

#assigning one value to multiple variables
a = b = c = 4
#displaying the values
print(a)
print(b)
print(c)  

Output:

4
4
4

Explanation:

In the above code, all three variables (a, b, c) are assigned the same value, which is 4. In this code, the variables are differentiated through ‘=’.

Assigning Multiple Values to Multiple variables:

Python allows assigning different values to different variables in a single line. For which we use the ‘,’ operators. In this kind of declaration, we need to ensure that the number of values is the same as the number of variables. Otherwise, it will throw an error.

For example,

#single line declaration of multiple value
 a, b, c = 1, “TutorialAndExample”, 10.5
# displaying value
print(a)
print(b)
print(c)

Outputs:

1
TutorialAndExample
10.5

Explanation:

In the above code, three variables (a,b,c) are assigned three different values. The first variable, a, is assigned a value of 1, an integer. The second variable, b, is assigned a String which is TutorialAndExample. The third variable, c, is assigned a float value which is 10.5.

Local Variables & Global Variables

Local and global variables are defined based on the position where it is declared. This is very important to understand these two terms and be able to differentiate if a variable is local or global.

Local Variable:

If a variable is declared inside the function, it is called a local variable. We cannot call local variables outside the function because they are defined and declared inside it.

Let’s understand with an example.

# This function is using local variable 
def fun ( ):
     age = 20
     print ( age )


fun ( ) 

Output:

20

Global Variable:

If a variable is declared outside the function, it is called a global variable. We use global variables inside the function, although they are defined and declared outside it.

Let’s understand with an example.

# This function is using global variable
def fun ( ):
    print (age)


age = 20
fun ( )

Output:

20

We can change a local variable to a global one using the keyword “global” in the function. We only use this keyword frequently when we want to change the value.

def fun ( ):
     global x
     x = “TutorialAndExample”
     print(x)
fun ( )
print(“Hi! Welcome to” + x)

Output:

TutorialAndExample
Hi! Welcome to TutorialAndExample

Conclusion

  • A variable is a container storing a value that can be changed anytime throughout the program.
  • A variable can be created using the syntax variable_name = value.
  • Any variable name should be descriptive. Since it will help the programmer to understand the code better. 

Related Topics

How to Declare a Variable in Python?

The concept of constants and variables is something that we are studying right from our primary classes. We know that constants are the fixed values whereas variables are those whose...

4 minutes read.

Flutter Python

The flutter is a frame work available in the python programming language, to create web applications, mobile apps. The flutter is generally used for the development of the backend of...

3 minutes read.

Data Structures and Algorithms Using Python | Part 1

Data Structures: Data Structure is defined as a way to organize and store the data so that we can access the data and work more efficiently. Data structures also describe the...

18 minutes read.

Sublime Python

SUBLIME: A compact, cross-platform code editor called Sublime Text 3 (ST3) is well-known for its quickness, usability, and robust community support. Although it's a fantastic editor out of the box, its...

6 minutes read.

How to Reverse a number in Python?

In Python, conditional statements can be combined with the list() method, slice() method, recursion() method, and other predefined techniques to generate reverse logical functions. The reverse() method is the most...

7 minutes read.

OSError in Python

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

4 minutes read.

Python Empty Tuple

How to Create an Empty Tuple Tuple A tuple is a data structure used to store non-homogeneous data elements. These non-homogeneous data elements consist of integer data type, character data type, String...

3 minutes read.

Python Sending Email

Python Sending Email Simple Mail Transfer Protocol (SMTP) is used to handle sending e-mail and routing e-mail between mail servers. When we send an email either form a web-application or from a local software...

3 minutes read.

Return Statement In Python

Python Return Statement The return statement is generally used for the execution ending and returns the value back to the caller. The return statement can return all types of values and...

2 minutes read.

Python Set update() method

Python Set update() method The set.update() method in Python updates the current set, by adding items from another set. If an element is common in both the sets, only one appearance of this item...

1 minute read.

Python Bitwise Operators

When used with variables and objects in an expression, operators are tokens that carry out calculations. The variables and items to which the computation is applied are known as operands....

5 minutes read.

Python Debugger

In this tutorial, we will understand what is debugging in general. Then we will realize what the python debugger means and what is the method to perform it. Now, let us...

3 minutes read.

Cube Root in Python

In general, the cube is a three-dimensional solid figure that has 6 square faces. It is also called a geometrical shape with six equal faces, eight vertices, and twelve edges....

3 minutes read.

Adding item to a python dictionary

The dictionary is one of python’s built-in data structures where it stores key-value pairs. A dictionary is a collection of ordered values that can be changeable. We can add, modify,...

3 minutes read.

Nested Tuple in Python

If you are a Python learner, this page contains all the information that helps you know about nested tuple and how to access it in python. What is a Tuple? Multiple items...

4 minutes read.

Ternary operators in python

Starting from Python version 2.5, ternary operators are also known as Conditional operators. Using these operators, we can evaluate any problem based on a condition. It is an alternative and...

4 minutes read.

Python all() Function

Python all() Function The all() function in Python returns a Boolean value ‘True’ if all the items in iterable are true or if the iterable object is empty, else it returns False. Syntax all(iterable) Parameter Iterable: An iterable object...

1 minute read.

Python Classification

Identification and grouping of items or concepts into specified categories this process is known the classification. Data can be separated and sorted in data management according to predetermined criteria for...

6 minutes read.

Assertion error in python

In this article, we will discuss assertions in the python programming language. Assertion: Assertions are a way of telling a program to test a certain condition and trigger an error if the...

3 minutes read.

Python TCP Server

The TCP server library is also known as the socket library. Socket programming is the method of connecting two nodes through a network to form communication between two nodes. In...

3 minutes read.