Python Variables, Creating Python Variables, Assigning Values to Variables, Variable Types in Python, Global and Local Variables in Python.
Variables in Python
What is a Variable?
• Variable is a named memory location to store the temporary data within a program.
• We have two types of memory in a computer environment (Temporary Memory- RAM and Permanent Memory – ROM), variables store in the Temporary memory (RAM).
• In Python, We do not need to declare variables before using them or declare their type. A variable is created the moment we first assign a value to it.
• A variable is a name given to a memory location. It is the basic unit of storage in a program.
Rules for creating variables in Python:
• A variable name must start with a letter or the underscore character.
• A variable name cannot start with a number.
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).
• Variable names are case-sensitive.
• The reserved words(keywords) cannot be used to name the variable.
Python has no command for declaring a variable. A variable is created the moment you first assign a value to it.
# declaring the variables
x = 123
y = “G C Rddy”
# Print variables
G C Reddy
Assigning a single value to multiple variables:
a = b = c = 10
Assigning different values to multiple variables:
a, b, c = 1, 20.2, “GCReddy Info”
Get the Type
We can get the data type of a variable with the type() built-in function.
x = 100
y = “India”
Global and Local Variables in Python:
Variables that are defined inside a function body have a local scope, and those defined outside have a global scope.
This means that local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the program body by all functions.
x = 100 # Global variable
y=200 # Local variable
Delete a Variable
We can also delete a variable using del command.
print (a); #123
print(a); # It will show error
Variable type in Python:
Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, data types are actually classes and variables are instances (objects) of these classes.
Python has five standard data types −