Book Image

Mastering Python Scripting for System Administrators

By : Ganesh Sanjiv Naik
Book Image

Mastering Python Scripting for System Administrators

By: Ganesh Sanjiv Naik

Overview of this book

Python has evolved over time and extended its features in relation to every possible IT operation. Python is simple to learn, yet has powerful libraries that can be used to build powerful Python scripts for solving real-world problems and automating administrators' routine activities. The objective of this book is to walk through a series of projects that will teach readers Python scripting with each project. This book will initially cover Python installation and quickly revise basic to advanced programming fundamentals. The book will then focus on the development process as a whole, from setup to planning to building different tools. It will include IT administrators' routine activities (text processing, regular expressions, file archiving, and encryption), network administration (socket programming, email handling, the remote controlling of devices using telnet/ssh, and protocols such as SNMP/DHCP), building graphical user interface, working with websites (Apache log file processing, SOAP and REST APIs communication, and web scraping), and database administration (MySQL and similar database data administration, data analytics, and reporting). By the end of this book, you will be able to use the latest features of Python and be able to build powerful tools that will solve challenging, real-world tasks
Table of Contents (21 chapters)

Tuples

Python's tuple data structure is immutable, meaning we cannot change the elements of the tuples. Basically, a tuple is a sequence of values that are separated by commas and are enclosed in parentheses ( ). Like lists, tuples are an ordered sequence of elements:

>>> t1 = 'h', 'e', 'l', 'l', 'o'

Tuples are enclosed in parentheses ( ):

>>> t1 = ('h', 'e', 'l', 'l', 'o')

You can also create a tuple with a single element. You just have to put a final comma in the tuple:

>>> t1 = 'h',
>>> type(t1)
<type 'tuple'>

A value in parentheses is not a tuple:

>>> t1 = ('a')
>>> type(t1)
<type 'str'>

We can create an empty tuple using the tuple() function:

>>> t1 = tuple()
>>> print (t1)
()

If the argument is a sequence (string, list, or tuple), the result is a tuple with the elements of the sequence:

>>> t = tuple('mumbai')
>>> print t
('m', 'u', 'm', 'b', 'a', 'i')

Tuples have values between parentheses ( ) separated by commas:

>>> t = ('a', 'b', 'c', 'd', 'e')
>>> print t[0]
'a'

The slice operator selects a range of elements.

>>> print t[1:3]
('b', 'c')

Accessing values in tuples

To access values in a tuple, use the square brackets for slicing along with the index or indices to obtain the value available at that index or indices, as shown in the following example:

#!/usr/bin/python3
cities = ('Mumbai', 'Bangalore', 'Chennai', 'Pune')
numbers = (1, 2, 3, 4, 5, 6, 7)
print (cities[3])
print (numbers[1:6])

Output:
Pune
(2, 3, 4, 5)

Updating tuples

Tuple updating is not possible in Python, as tuples are immutable. But you can create a new tuple with an existing tuple, as shown in the following example:

#!/usr/bin/python3
cities = ('Mumbai', 'Bangalore', 'Chennai', 'Pune')
numbers = (1,2,3,4,5,6,7)
tuple1 = cities + numbers
print(tuple1)

Output:
('Mumbai', 'Bangalore', 'Chennai', 'Pune', 1, 2, 3, 4, 5, 6, 7)

Deleting tuple elements

We cannot remove individual tuple elements. So, to remove an entire tuple explicitly, use the del statement. Refer to the following example:

#!/usr/bin/python3
cities = ('Mumbai', 'Bangalore', 'Chennai', 'Pune')
print ("Before deleting: ", cities)
del cities
print ("After deleting: ", cities)

Output:
Before deleting: ('Mumbai', 'Bangalore', 'Chennai', 'Pune')
Traceback (most recent call last):
File "01.py", line 5, in <module>
print ("After deleting: ", cities)
NameError: name 'cities' is not defined

Basic tuple operations

Like lists, there are five basic tuple operations:

  • Concatenation
  • Repetition
  • Length
  • Membership
  • Iteration

Description

Expression

Results

Iteration

for x in (45,58,99) : print (x,end = ' ')

45 58 99

Repetition

('Python') * 3

('python', 'python', 'python')

Length

len(45, 58, 99, 65)

4

Concatenation

(30, 50, 60) + ('Hello', 75, 66)

(30,50,60,'Hello',75,66)

Membership

45 in (45,58,99,65)

True

Indexing, slicing, and matrices

Tuple indices work the same way as list indices. Values can be accessed using index. If you try to read or write an element that does not exist, you get IndexError. If an index has a negative value, it counts backward from the end of the list.

Now, we will create a tuple named cities and perform some index operations:

cities = ('Mumbai', 'Bangalore', 'Chennai', 'Pune')

Description

Expression

Results

Index starts at zero

cities[2]

'Chennai'

Slicing: getting sections

cities[1:]

('Bangalore', 'Chennai', 'Pune')

Negative: count from the right

cities[-3]

'Bangalore'

max() and min()

Using the max() and min() functions, we can find the highest and lowest values from the tuple. These functions allow us to find out information about quantitative data. Let's look at an example:

>>> numbers = (50, 80,98, 110.5, 75, 150.58)
>>> print(max(numbers))
150.58
>>>

Using max(), we will get the highest value in our tuple. Similarly, we can use the min() function:

>>> numbers = (50, 80,98, 110.5, 75, 150.58)
>>> print(min(numbers))
50
>>>

So, here we are getting the minimum value.