python variables

Python Variables-: Like any other programming language python Variables are nothing but reserved memory locations to store values. This means that when we create a variable we reserve some space in memory.

Based on the data type of a variable the interpreter allocates memory and decides what can be stored in the reserved memory. So we assigning different data types to variables we can store integers, decimals or characters in these variables.

Variables are the example of identifiers. An Identifier is used to identify the literals used in the program. The rules to name an identifier are given below.

  • The first character of the variable must be an alphabet or underscore ( _ ).
  • Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &, *).
  • Identifier name must not be similar to any keyword defined in the language.
  • All the characters except the first character may be an alphabet of lower-case(a-z), upper-case (A-Z), underscore or digit (0-9).
  • Identifier names are case sensitive for example my name, and MyName is not the same.

 

Types of variable in Python-:  In the python has Three types variable

  1. Local variable
  2. Non local variable
  3. Global variable
def fact(n):
    """Return the factorial of the given number."""
    r = 1
    while n > 0:
        r = r * n
        n = n - 1
    return r

Both the variables r and n are local to any particular call of the factorial function,changes to them made when the function is executing have no effect on any variables outside the function. Any variables in the parameter list of a function and any variables created within a function by an assignment (like r = 1 in fact) are local to the function.

We can explicitly make a variable global by declaring it so before the variable is used, using the global statement. Global variables can be accessed and changed by the function. They exist outside the function and can also be accessed and changed by other functions that declare them global or by code that’s not within a function. Here is an example that shows the difference between local and global variables…

>>> def fun():
...     global a
...     a = 1
...     b = 2

This example defines a function that treats a as a global variable and b as a local variable and attempts to modify both a and b. another example of

>>> a = "one"
>>> b = "two"

>>> fun()
>>> a
1
>>> b
'two'

The assignment to a within fun is an assignment to the global variable a also existing outside fun. Because a is designated global in fun, the assignment modifies that global variable to hold the value 1 instead of the value “one”. The same are not true for b. the local variable called b inside fun starts out referring to the same value as the variable b outside fun but the assignment causes b to point to a new value that’s local to the function fun.

Similar to the global statement is the non-local statement which causes an identifier to refer to a previously bound variable in the closest enclosing scope. The point is that global is used for a top-level variable whereas non local can refer to any variable in an enclosing scope. For example

g_var = 0                               1
nl_var = 0                              1
print("top level-> g_var: {0} nl_var: {1}".format(g_var, nl_var))
def test():
nl_var = 2                              2
print("in test-> g_var: {0} nl_var: {1}".format(g_var, nl_var))
def inner_test():

global g_var                             3
nonlocal nl_var                          4
g_var = 1
nl_var = 4
print("in inner_test-> g_var: {0} nl_var: {1}".format(g_var,
nl_var))

inner_test()
print("in test-> g_var: {0} nl_var: {1}".format(g_var, nl_var))

test()
print("top level-> g_var: {0} nl_var: {1}".format(g_var, nl_var))

 

g_var in inner_test binds top-level g_var.
nl_var in inner_test binds to nl_var in test.
g_var in inner_test binds top-level g_var.
nl_var in inner_test binds to nl_var in test.

The out put of this programme

top level-> g_var: 0 nl_var: 0
in test-> g_var: 0 nl_var: 2
in inner_test-> g_var: 1 nl_var: 4
in test-> g_var: 1 nl_var: 4
top level-> g_var: 1 nl_var: 0

the value of the top-level nl_var has not been affected which would happen if inner_test contained the line global nl_var.

Global variable vs local variable-: Assuming that x = 5, what will be the value of x after funct_1() below executes? After funct_2() executes?

def funct_1():
    x = 3
def funct_2():
    global x
    x = 2

 

Assign function to variable-:Functions can be assigned like other Python objects to variables as like

>>> def f_to_kelvin(degrees_f):                      1
...     return 273.15 + (degrees_f - 32) * 5 / 9
...
>>> def c_to_kelvin(degrees_c):                      2
...     return 273.15 + degrees_c
...
>>> abs_temperature = f_to_kelvin                    3
>>> abs_temperature(32)
273.15
>>> abs_temperature = c_to_kelvin                    3
>>> abs_temperature(0)
273.15
  • Defines the f_to_kelvin kelvin function
  • Defines the c_to_kelvin function
  • Assigns function to variable

 

Leave a Reply

Your email address will not be published. Required fields are marked *