Variables In Python

What Are Variables?

In programming, a variable is a container for storing data. Variables are stored in the computer’s memory. Each variable has its own unique memory address. Don’t bother about Id now, you will learn about it in detail in the upcoming post.

Creating Variables In Python

In Python, it is easier to create variables when compared to other languages. In languages like C, C++, and Java, we must specify the type of the variable before assigning it a value. But in Python, there’s no type of declaration needed.

Following is the syntax for creating variables.

Syntax : variable_name = value

Here ‘=’ is known as an ‘Assignment Operator’, it assigns the value on the right to the variable_name on the left.

(There are so many operators available and ‘=’ is one of them)

Example For Creating A Variable In Python

And we can assign values to multiple variables in single line.

Accessing Variables In Python

Assume, you are creating a program to add two numbers.

When ‘x+y’ gets executed the values x and y will be replaced with 10 and 20 which gives 30 as the output.

Updating Variables In Python

In Python you can change the value of a variable by assigning it with a new value.

Initially x is assigned with 10, but when we executed ‘x = 25’ command  the value of x got replaced with 25.

Deleting Variables In Python

We can delete a variable by using ‘del’ keyword in Python.

Here, when we executed ‘del y’ command the variable ‘y’ will be remove from memory. So when we tried to access it again it raises a ‘NameError’.

Naming Variables In Python

Note: Variables are case sensitive in Python.

Do’s :-

  • variable names can start with underscore (_) and letters.
  • variable names can contain numbers in the middle or at the end.

Dont’s :-

  • variable names shouldn’t start with numbers or digits.
  • variable names shouldn’t contain spaces and symbols. (except underscore)
  • Keywords shouldn’t be used as variable names.

Scope Of The Variable

There are Two types of variable in python.

  • Global Variable
  • Local Variable

Global Variable: If you define a variable at the top level of your script or module or function, this is a global variable.

You can use everywhere in your program. even you can access inside the function as well.

Local Variable: If you define a variable at any function, that variable is called a local variable.

You can only access the variable within the function. You cannot access it outside the function.

Do you know?
Variables In Python This article is contribute by Nisha Nishanth If you want share your knowledge on Study4Geeks then go to login section.