Python for Linux Admins -II

In this part we will continue our journey with Python.

Note that every thing in Python is an Object and it has a unique id and it has a type e.g

>>> x = 2

>>> id(x)

505498008

>>> type(x)

#showing class is integer

Now lets take a look at below example

>>> y = “”Hyp3ri0n””

>>> id(y)

16153152

>>> type(y)

#showing class is string

Now objects in python can be mutable or they can be immutable.

Mutable can change value , but immutable may not.

Mutable = lists, dictionary

Immutable = numbers, strings, tuples.

Here is a program used to replace a value as per Python version 2 works in 3 but is obsolete.

>>> z = 10

>>> s = “”My age is %s”” %z        #Note  %s is used to change the value

>>> print (s)

My age is 10

In Python 3 The above code will become

>>> z = 10

>>> s = “”My age is {}”” .format(z)

>>> print (s)

My age is 10

To add a new line we use \n

e.g

>>> s=””My age is 10\nI am happy””

>>>print(s)

My age is 10

I am happy

Functions:

Functions in Python is a method of reusing code. These are very important to understand for our next example.

#!/usr/bin/python3
def main ():
testfunc()
def testfunc():
print(‘Welcome to ITpings’)
if __name__ == ‘__main__’:main()

Now let me explain step by step

To define a function we use def key and functionname () in our case we defined a testfunc()

if we add : at the end of function it means that there must be a value after and the line below must not be empty

In our case the testfucn has a one line code which will print Welcome to ITpings

This function testfunc will be called by the testfunc() under the main(): , because it is duty of main function to call its sub functions.

The last line is a default so that a function must work within a function.

We can also add arguments within the brackets of functions such as

#!/usr/bin/python3
def main ():
testfunc(1,2,3)
def testfunc(a,b,c):
print(‘The numbers are’,a,b,c)
if __name__ == ‘__main__’:main()

The above will print

The numbers are 1 2 3

Now for our better understanding we can use the below program to reuse a same function more than once

#!/usr/bin/python3
def main ():
testfunc()
def testfunc():
for i in range(10):
print(i, end= ‘ ‘)
if __name__ == ‘__main__’:main()

The above will print

0 1 2 3 4 5 6 7 8 9

Now to reuse the same function we will add

#!/usr/bin/python3
def main ():
testfunc()

testfunc()

testfunc()

def testfunc():
for i in range(10):
print(i, end= ‘ ‘)
if __name__ == ‘__main__’:main()

And now it will print

0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9

Note: Indenting is very important in Python the default rule is to use 4 spaces.

 

Thanks,

Salman Aftab