Python Variables and Assignment
A variable is a name, which represents a value. To understand it, open a Python terminal and run below command.
id = 10
You will not see any result on screen. Then what happens here? This is an assignment statement, where id is a variable and 10 is the value assigned to the variable.
A single equal (=) is an assignment operator. Where left side of the operator is the variable and right side operator is a value.
Once a value is assigned to the variable, we can use variable name anywhere in a python program instead of using value.
Variable Names in Python
Similar to other programming languages, Python also have limitations on defining variable names:
- A variable name must start with a letter or the underscore.
- A variable name cannot start with a number.
- A variable name can have a single character or string up to 79 characters.
- A variable name contains only alpha-numeric characters and underscores (Like: A-Z, a-z, 0-9, and _ ).
- A Variable names are case-sensitive (id, Id and ID are different variables in Python).
Variable Assignment Examples
Below is the some valid python variable names”
_id = 10 name = "rahul" name = 'rahul' address_1 = "123/3 my address"
You can also assign the same value to multiple variables in single command.
a = b = c = "green"
Also you can assingle multiple values to multiple variables in a single command.
a, b, c = "green", "yellow", "blue"
Local vs Global Variable
A local variable is defined in a function block. It is accessible within the function only. Once the function execution completed, the variable is destroyed.
A Global variable is variable defined in Python program. It is not defined in any function block. It is accessible to entire Python program including functions. A Global variable destroyed only once the script execution completed.
Below is a sample program to show you difference between local and global variables. Here “a” is a global variable and “b” is a local variable of function myfun().
a = "Rahul" def myfun(): b = "TecAdmin" print(a) print(b) myfun() print(a) print(b) ## You will get error - 'b' is not defined