Simple while loop

In [ ]:
n = 23
r = True

while r:
    guess= int(input('Enter an integer: '))
    
    if guess == n:
        print('yes')
        r = False
    elif guess < n:
        print('no')
    else:
        print('no1')
else:
    print('done')
    
print('yes done')        

Simple backup

In [9]:
import os
import time

source = '/home/akash/funny3'

target = '/home/akash/funny3zip'

if not os.path.exists(target): 
    os.mkdir(target)
    
today = target + os.sep + time.strftime('%Y%m%d')

now = time.strftime('%H%M%S')

target = today+os.sep+now+'.zip'

if not os.path.exists(today): 
    os.mkdir(today)
    print('created today')
    
zip_command = "zip -r {0} {1}".format(target, ' '.join(source)) 
# Run the backup 
print ("Zip command is:")
print(zip_command)
print("Running:")
if os.system(zip_command) == 0:
    print('Successful backup to', target)
else:
    print('Backup FAILED')
created today
Zip command is:
zip -r /home/akash/funny3zip/20200624/145038.zip / h o m e / a k a s h / f u n n y 3
Running:
Backup FAILED

A simple class

In [15]:
class Robot:
    
    # a class variable
    
    population = 0
    
    def __init__(self, name):
        # initialized the data
        self.name = name
        print("(Initializing {})".format(self.name))
        
        Robot.population += 1
        
    def die(self):
        # Dying
        
        print("{} is being destroyed".format(self.name))
        
        Robot.population -= 1
        
        if Robot.population == 0:
            print("{} was the last one".format(self.name))
        else:
            print("There are still {:d} robots working".format(Robot.population))
            
    def say_hi(self):
        # greeting
        
        print("Greetings, i am".format(self.name))
        
    @classmethod
    def how_many(cls):
        ## prints current population
        print(" we have {:d} robots. ". format(cls.population))
In [16]:
droid1 = Robot("R2")
droid1.say_hi()
Robot.how_many()

droid2 = Robot("R3")
droid2.say_hi()
Robot.how_many()

print("they can work now")

print("destroyinnng...")

droid1.die()
droid2.die()

Robot.how_many()
(Initializing R2)
Greetings, i am
 we have 1 robots. 
(Initializing R3)
Greetings, i am
 we have 2 robots. 
they can work now
destroyinnng...
R2 is being destroyed
There are still 1 robots working
R3 is being destroyed
R3 was the last one
 we have 0 robots. 

Inheritance

In [42]:
class SchoolMember:
    def __init__(self, name, age):
        self.name = name
        self.age = age
        print('Initialized SchoolMember: {})'.format(self.name))
        
    def tell(self):
        '''Tell my details.''' 
        print('Name:"{}" Age:"{}"'.format(self.name, self.age))
        
        
class Teacher(SchoolMember):
    
    def __init__(self, name, age, salary):
        SchoolMember.__init__(self, name, age)
        self.salary = salary
        print('Initialized Teacher: {})'.format(self.name))
              
    def tell(self):
        SchoolMember.tell(self)
        print('Salary: "{:d}"'.format(self.salary))

class Student(SchoolMember):
    
    def __init__(self, name, age, marks):
        SchoolMember.__init__(self, name, age)
        self.marks = marks
        print('Initialized Student: {})'.format(self.name))
              
    def tell(self):
        
        SchoolMember.tell(self)
        print('Marks: "{:d}"'.format(self.marks)) 
In [44]:
t = Teacher('A', 40, 20000)

s = Student('me', 25, 75)

m = [t, s]

for members in m:
    members.tell()
Initialized SchoolMember: A)
Initialized Teacher: A)
Initialized SchoolMember: me)
Initialized Student: me)
Name:"A" Age:"40"
Salary: "20000"
Name:"me" Age:"25"
Marks: "75"

Exceptions

In [47]:
try:
    text = input("enter-->")
except EOFError:
    print('why eof')
else:
    print("you entered {}".format(text))
enter-->sd
you entered sd

Finally

In [ ]:
import sys
import time 
f = None

try:
    f = open("poem.txt") # Our usual file-reading idiom 
    while True:
        line = f.readline()
        if len(line) == 0:
            break
        print line, sys.stdout.flush()
        print "Press ctrl+c now" # To make sure it runs for a while
        time.sleep(2) 
except IOError:
    print "Could not find file poem.txt" 
except KeyboardInterrupt:
    print "!! You cancelled the reading from the file."
finally: 
    if f: f.close()
        print "(Cleaning up: Closed the file)"

With statement

In [ ]:
with open('file.txt') as w:
    for line in w:
        print(line)

Standard Libraries

In [49]:
## sys module - system specific 

# print(sys.argv)
In [50]:
sys.version_info
Out[50]:
sys.version_info(major=3, minor=7, micro=3, releaselevel='final', serial=0)
In [ ]:
## Loggin module


import os, platform, logging

if platform.platform().startswith('Windows'):
    logging_file = os.path.join(os.getenv('HOMEDRIVE'), os.getenv('HOMEPATH'), 'test.log')
else: logging_file = os.path.join(os.getenv('HOME'), 'test.log')

print "Logging to", logging_file

logging.basicConfig( level=logging.DEBUG, format='%(asctime)s : %(levelname)s : %(message)s', filename = logging_file, filemode = 'w', )

logging.debug("Start of the program")
logging.info("Doing something")
logging.warning("Dying now")

Lambda Forms

In [51]:
points = [ { 'x' : 2, 'y' : 3 }, { 'x' : 4, 'y' : 1 } ]
points.sort(key=lambda i : i['y'])
print(points)
[{'x': 4, 'y': 1}, {'x': 2, 'y': 3}]

List Comprehensions

In [52]:
listone = [2, 3, 4]
listtwo = [2*i for i in listone if i > 2]
listtwo
Out[52]:
[6, 8]

Assert

In [53]:
mylist = ['item']
assert len(mylist) >= 1
mylist.pop()
Out[53]:
'item'
In [54]:
assert len(mylist) >= 1
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-54-927142ca25aa> in <module>
----> 1 assert len(mylist) >= 1

AssertionError: 

Decorators

In [ ]:
from time import sleep
from functools import wraps
import logging
logging.basicConfig()
log = logging.getLogger("retry")


def retry(f):
    @wraps(f)
    def wrapped_f(*args, **kwargs):
        MAX_ATTEMPTS = 5
        for attempt in range(1, MAX_ATTEMPTS + 1):
            try:
                return f(*args, **kwargs)
            except:
                log.exception("Attempt %s/%s failed : %s", attempt, MAX_ATTEMPTS, (args, kwargs))
                sleep(10 * attempt)
            log.critical("All %s attempts failed : %s", MAX_ATTEMPTS, (args, kwargs))
        return wrapped_f
    counter = 0


    
@retry
def save_to_database(arg):
    print "Write to a database or make a network call or etc."
    print "This will be automatically retried if exception is thrown."
    global counter
    counter += 1 # This will throw an exception in the first call # And will work fine in the second call (i.e. a retry)
    if counter < 2:
        raise ValueError(arg)
    
if __name__ == '__main__':
    save_to_database("Some bad value")

Command line arguments

In [ ]:
#!/usr/bin/python

import sys

# it's easy to print this list of course:
print(sys.argv)

# or it can be iterated via a for loop:

for i in range(len(sys.argv)):
    if i == 0:
        print("Function name: %s" % sys.argv[0])
    else:
        print("%d. argument: %s" % (i,sys.argv[i]))
In [ ]:
## OUTPUT 

$ python arguments.py arg1 arg2
['arguments.py', 'arg1', 'arg2']
Function name: arguments.py
1. argument: arg1
2. argument: arg2
$

System programming and Python

In [ ]:
## Packages:

os
platform
subprocess
shutils
glob
sys
In [55]:
import os

print(os.name)
posix

These names define the following operating systems:

posix Unix-like operating systems like Unix, Linux, BSD, Minix and others. nt Windows systems like "Windows 10", "Windows 8.1", "Windows 8", "Windows 7" and so on. java Java operating system.

In [ ]:
## Other common commands:

print(os.getcwd())
os.chdir("") ## Changes to the path mentioned
print(os.getcwd())

print(os.listdir()) ## names of the files of directory