Python 3 Variables


Variables are nothing but reserved memory locations to store value. This means when you create a variable you reserve some space in memory.


Python is completely object oriented and not "statically typed". You no need to declare variables before using them, or declare their type. Every variable in python is an object.

Every value in python has data type. Different data types in python are:

  • Numbers
  • String
  • List
  • Tuple
  • Dictionary

Python Numbers:

Number data types store numeric values. Number objects are created when you assign a value to them. For example:

var1 = 32
var2 = 42

Python supports two types of numbers:

  • Float
  • Integers

To define a floating point number, you may use the following:

pi = 3.14
print(pi)


You can redeclare variable even after you have declared once:

f = 0
print(f)

f = "cat"
print(f)

Concatenate Variables:

You can concatenate variables of same type.

f = "dog" + "cat"
print(f)

For concatenating variables of different data types you need to convert them into same data type

f = "Embedded" + str("123")
print(f)

Deleting Variables:

You can delete the variable by using "del"

f = "abc"
print(f)
del f
print(f)

When you run the above code, last line will give you error : "name 'f' is not defined"

Global vs Local Variables:

def someFunction():
     print(f)
f = "abc"
someFunction()

O/P: abc

In the above code as there was no local variable 'f' , value of global variable will b e used.

def someFunction():
     f="cad"
     print(f)
f = "abc"
someFunction()

O/P: cad

In the   above code as there was local variable, it got printed..

def someFunc():
        print(f)
        f="hello"
        print(f)

f="some thing"
someFunc()

The above code returns error, as we are trying to use f before it is assigned. Python assumes that we want local variable due to assignment of variable "f" in someFunc() , so the first print() statement throws error. Any variable which is declared inside a function is local, if it hasn't been declared as a global variable.

To tell python, that we want to use the global variable, we have to use the keyword "global".

def someFunc():
        global f
        print(f)
        f="hello"
        print(f)

f="some thing"
someFunc()
print(f)

O/P: something
hello
hello

Local variables created inside function cannot be accessed outside.

def someFunc():
        f="hello"
        print(f)

someFunc()
print(f)

This will throw an error in the last line.



 



Comments

Post a Comment

Popular posts from this blog

bb.utils.contains yocto

make config vs oldconfig vs defconfig vs menuconfig vs savedefconfig

PR, PN and PV Variable in Yocto