Python Variables

19 Feb, 2021
Python is not “statically typed”. 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.
The value stored in a variable can be changed during program execution.
A variable is only a name given to a memory location, all the operations done on the variable effects that memory location.
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 (name, Name and NAME are three different variables).
The reserved words(keywords) cannot be used naming the variable.
Let’s see the simple variable creation:
Python3
#!/usr / bin / python  # An integer assignmentage = 45  # A floating pointsalary = 1456.8  # A stringname = "John"  print(age)print(salary)print(name)
Output:
45
1456.8
John

Let’s see how to declare the variable and print the variable.
Python3
# declaring the varNumber = 100  # displayprint( Number)
Output:
100

We can re-declare the python variable once we have declared the variable already.
Python3
# declaring the varNumber = 100  # displayprint("Before declare: ", Number)  # re-declare the varNumber = 120.3    print("After re-declare:", Number)
Output:
Before declare:  100
After re-declare: 120.3

Also, Python allows assigning a single value to several variables simultaneously with “=” operators. For example: 
Python3
#!/usr / bin / python  a = b = c = 10  print(a)print(b)print(c)
Output:
10
10
10
Python allows adding different values in a single line with “,”operators.
Python3
#!/usr / bin / python  a, b, c = 1, 20.2, "GeeksforGeeks"  print(a)print(b)print(c)
Output:
1
20.2
GeeksforGeeks
If we use the same name, the variable starts referring to a new value and type. 
Python3
#!/usr / bin / python  a = 10a = "GeeksforGeeks"  print(a)
Output:
GeeksforGeeks
Python3
#!/usr / bin / python  a = 10b = 20print(a+b)  a = "Geeksfor"b = "Geeks"print(a+b)
30
GeeksforGeeks

No using for different types would produce error. 
Python3
#!/usr / bin / python  a = 10b = "Geeks"print(a+b)
Output : 
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Local variables are the ones that are defined and declared inside a function. We can not call this variable outside the function.
Python3
# This function uses global variable sdef f():    s = "Welcome geeks"    print(s)    f()
Output:
Welcome geeks

Global variables are the ones that are defined and declared outside a function, and we need to use them inside a function.
Python3
# This function has a variable with# name same as s.def f():    print(s)    # Global scopes = "I love Geeksforgeeks"f()
Output:
I love Geeksforgeeks

Global keyword is a keyword that allows a user to modify a variable outside of the current scope. It is used to create global variables from a non-global scope i.e inside a function. Global keyword is used inside a function only when we want to do assignments or when we want to change a variable. Global is not needed for printing and accessing.
Rules of global keyword:
If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.
Variables that are only referenced inside a function are implicitly global.
We Use global keyword to use a global variable inside a function.
There is no need to use global keyword outside a function.
Example:
Python3
# Python program to modify a global# value inside a function  x = 15    def change():      # using a global keyword    global x      # increment value of a by 5    x = x + 5    print("Value of x inside a function :", x)    change()print("Value of x outside a function :", x)
Output:
Value of x inside a function : 20
Value of x outside a function : 20

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 instance (object) of these classes.
Following are the standard or built-in data type of Python:
Numeric
Sequence Type
Boolean
Set
Dictionary
Example:
Python3
# numbericvar = 123print("Numbric data : ", var)  # Sequence TypeString1 = 'Welcome to the Geeks World'print("String with the use of Single Quotes: ")print(String1)  # Booleanprint(type(True))print(type(False))  # Creating a Set with# the use of a Stringset1 = set("GeeksForGeeks")print("\nSet with the use of String: ")print(set1)  # Creating a Dictionary# with Integer KeysDict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}print("\nDictionary with the use of Integer Keys: ")print(Dict)
Output:
Numbric data :  123
String with the use of Single Quotes: 
Welcome to the Geeks World
<class 'bool'>
<class 'bool'>

Set with the use of String: 
{'r', 'G', 'e', 'k', 'o', 's', 'F'}

Dictionary with the use of Integer Keys: 
{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Let, we assign a variable x to value 5, and another variable y to the variable x.
Python3
x = 5y = x
When Python looks at the first statement, what it does is that, first, it creates an object to represent the value 5. Then, it creates the variable x if it doesn’t exist and made it a reference to this new object 5. The second line causes Python to create the variable y, and it is not assigned with x, rather it is made to reference that object that x does. The net effect is that the variables x and y wind up referencing the same object. This situation, with multiple names referencing the same object, is called a Shared Reference in Python.Now, if we write:
Python3
x = 'Geeks'
This statement makes a new object to represent ‘Geeks’ and makes x to reference this new object.
Please refer Class, Object and Members for more details. 
Python3
# Python program to show that the variables with a value # assigned in class declaration, are class variables and# variables inside methods and constructors are instance# variables.    # Class for Computer Science Studentclass CSStudent:       # Class Variable    stream = 'cse'                   # The init method or constructor    def __init__(self, roll):             # Instance Variable            self.roll = roll           # Objects of CSStudent classa = CSStudent(101)b = CSStudent(102)    print(a.stream)  # prints "cse"print(b.stream)  # prints "cse"print(a.roll)    # prints 101    # Class variables can be accessed using class# name alsoprint(CSStudent.stream) # prints "cse"    
cse
cse
101
cse

kumar_satyam
Picked
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.