Skip to main content

Program Controls and loops in Python

Python Programming controls

The flow of program will be controlled with conditional statements where this flow 
  1. if condition
  2. if-else condition
  3. if-elif condition
  4. while loop
  5. while - else loop
  6. for loop
  7. for with if- else loop

if condition

Here I would like to work on program control statements, wherein relate some operating system functionalities so that, this would give some basic prototype for the sys admin scripts.
#!/usr/bin/python

# This illustrate if condition
# Filename      :       ifex.py

import os
d=os.listdir('/home/pavanbsd/pybin')
print d
f='ifex.py'
if f in d:
        print "File exists"
else:
        print "Not found..."

if-elif-else ladder

No worries, coming soon...
When you need the task that need to be done repeatedly then your choice is using loops. Python provides two simple loop constructs easy to use! More powerful then other scripting compare to, it has 'else' block.

while loop

Understand the power of while loop, which would check the condition for every iteration completion.
#!/usr/bin/python

# This is to illustrate while loop
# print 0-10 numbers

i=0
sum=0
while i<=10:
        print i
        sum=sum+i
        i+=1
print "after a while, sum of 0-10:", sum
Execution of the above script
:~/pybin$ ./while1.py
0
1
2
3
4
5
6
7
8
9
10
after a while, sum of 0-10:55
combine the above all logical constructs we can make a menu driven script
#!/usr/bin/python
import os, sys

print "System monitoring"
while True:
        print "c-CPU utilization\nm-Mem utilization\nd-Disk space\n"
        ch=raw_input('Enter your choice(q-quit):')
        if ch=='c':
                        print "cpu load"
                        os.system("uptime")
        elif ch=='m':
                        print "free -m"
                        os.system("free -m")
        elif ch=='d':
                        print "df -h"
                        os.system("df -hT")
        elif ch=='q':
                print "Exiting loop"
                break
        else:
                        print "invalid choice"


execution of the above example
:~/pybin$ ./menu.py
System monitoring
c-CPU utilization
m-Mem utilization
d-Disk space

Enter your choice(q-quit):c
cpu load
 08:16:49 up  1:14,  2 users,  load average: 0.17, 0.12, 0.14
c-CPU utilization
m-Mem utilization
d-Disk space

Enter your choice(q-quit):m
free -m
             total       used       free     shared    buffers     cached
Mem:          3500        288       3212          0         42        129
-/+ buffers/cache:        116       3383
Swap:         1021          0       1021
c-CPU utilization
m-Mem utilization
d-Disk space

Enter your choice(q-quit):d
df -h
df: `/var/lib/lightdm/.gvfs': Permission denied
Filesystem     Type      Size  Used Avail Use% Mounted on
/dev/sda1      ext4      6.8G  4.7G  1.9G  72% /
udev           devtmpfs  1.8G  4.0K  1.8G   1% /dev
tmpfs          tmpfs     701M  780K  700M   1% /run
none           tmpfs     5.0M     0  5.0M   0% /run/lock
none           tmpfs     1.8G  144K  1.8G   1% /run/shm
/dev/sdb5      ext4       21G   44M   20G   1% /tmp
/dev/sdc1      ext4      9.8G   23M  9.2G   1% /app
c-CPU utilization
m-Mem utilization
d-Disk space

Enter your choice(q-quit):q
Exiting loop

Comments

Popular posts from this blog

Python Sets and Dictionaries

Python Sets Python Maps examples A mapping object maps hashable values to arbitrary objects. Mappings are mutable objects. There is currently only one standard mapping type, the dictionary. Dictionaries consist of pairs (called items) of keys and their corresponding values. Dictionaries can be created by placing a comma-separated list of key: value pairs within curly braces Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples. Python Set Operations and methods Python Set methods continueed >>> SET={'new','old','list','new'} >>> SET set(['new', 'old', 'list']) Lets play with set operations, it is more like school math here... >>> s={1,2,3,4} >>> k={3,4,5,6} >>> len(s) 4 >>> len(k) 4 >>> 1 in s True >>...

AWS Auto Scaling using Python Boto3

Auto Scaling Group in AWS configure using Python Boto3  What is Auto Scaling means?  This is key capability or power of Cloud Computing Engineers believe in their skills on scaling abilities.  Amazon EC2 Auto Scaling helps to maintain application availability and lets automatically add or remove EC2 instances using scaling policies that we define.  There are 2 types of scaling policies : Dynamic or predictive. These scaling policies let us add or remove EC2 instances capacity to service established or real-time demand patterns. It contains various steps involved in Auto Scaling process using Python Boto3 we will explore every step that accumulate to form a complete automation solution for a DevOps project. ASG Groups associated with ELB and EC2 instances   Understanding AWS Auto scaling configuration steps Check any running instances Create launch configuration Configure ASG for Auto scaling Verify the configuration Disable Auto Scaling In order to setup A...