Sunday, October 27, 2019

Python : Variables


A Python variable is a reserved memory location to store values. In other words, a variable in a python program gives data to the computer for processing.

Every value in Python has a datatype. Different data types in Python are Numbers, List, Tuple, Strings, Dictionary, etc. Variables can be declared by any name or even alphabets like a, aa, abc, etc.


Example

a=100
print a


Redeclaring a variable - Crazy!!

# Declare a variable and initialize it
f = 0
print(f)
# re-declaring the variable works
f = 'guru99'
print(f)

Concatenating String

a="Guru"
b = 99
print a+b

The above will give error because the data type of B is int str(b) to be done to declare it as String

Global vs local scope variables

# Declare a variable and initialize it
f = 101
print(f)
# Global vs. local variables in functions
def someFunction():
# global f
    f = 'I am learning Python'
    print(f)
someFunction()
print(f)

Variable "f" is global in scope and is assigned value 101 which is printed in output
Variable f is again declared in function and assumes local scope. It is assigned value "I am learning Python." which is printed out as an output. This variable is different from the global variable "f" define earlier
Once the function call is over, the local variable f is destroyed. At line 12, when we again, print the value of "f" is it displays the value of global variable f=101

Now, if we use global keyword, even if it is defined within a function, this becomes a global scoped variables

f = 101;
print f
# Global vs.local variables in functions
def someFunction():
  global f
  print f
  f = "changing global variable"
someFunction()
print f

Variable "f" is global in scope and is assigned value 101 which is printed in output
Variable f is declared using the keyword global. This is NOT a local variable, but the same global variable declared earlier. Hence when we print its value, the output is 101
We changed the value of "f" inside the function. Once the function call is over, the changed value of the variable "f" persists. At line 12, when we again, print the value of "f" is it displays the value "changing global variable"

Deleting a variable

f = 11;
print(f)
del f
print(f)

This gives error at the 4th line saying the variable is not defined


References:
https://www.guru99.com/variables-in-python.html

1 comment: