Jan 19, 2019

Python Generator

#################################################
## Uses of Generators:
##   1) It will automatically takes care of __iter__() and next()/__next__() 
##   2) More easy to use
##   3) It won't load everything in memory, so it consumes less memory (memory efficient)
#################################################

def generatorFunction(listA):
for each in listA:
yield each

print '------'
ic = generatorFunction(['A','B','C'])
for each in ic:
print(each)

print '------'
ic = generatorFunction(['A','B','C'])
print (ic)
print(next(ic))
print(next(ic))
print(next(ic))
#print(next(ic)) #This raises StopIteration

print (ic)

print '$$$$$$$$'
# This will not print anything, since generator got exhausted as we earlier called next() many times already
# You have to re-initialize generator object again
for each in ic: 
print(each)

ic = generatorFunction(['A','B','C'])
print '#########'
for each in ic:
print(each)


Output:
------
A
B
C
------
<generator object generatorFunction at 0x7f82ddcaca50>
A
B
C
<generator object generatorFunction at 0x7f82ddcaca50>
--$$$$$----
--#####----
A
B
C

Python Iterator Iterbale

################################################
## Writing own iterators
## Two ways:
##    1) using __iter__ and __next__ for Python 3.0
##       using __iter__ and next() for Python 2.7      
##    2) using generator functions
##    3) They can go only forward, no backwards
################################################

class IterClass:
def __init__(self, listA):
self.index = 0
self.elments = listA
def __iter__(self): #To make an object sequence
return self
def next(self): #in 2.7 use next(), in 3.0 use __next__()
if self.index >= len(self.elments):
raise StopIteration
index = self.index
self.index += 1
return self.elments[index]

ic = IterClass(['A','B','C'])
for each in ic:
print each
print '------'
ic = IterClass(['A','B','C'])
print(next(ic))
print(next(ic))
print(next(ic))
#print(next(ic)) #This raoses StopIteration
print'-------'

ll = range(0,5)
print ll

#List object is iterable but not iterator
print dir(ll) #it has __iter__ only, but no next/__next__ method
#next(ll) will fail

ll_iter = ll.__iter__()
print dir(ll_iter) #it has next/__next__ method


print ll_iter
print dir(ll_iter)
print next(ll_iter)
print next(ll_iter)
print next(ll_iter)
print next(ll_iter)
print next(ll_iter)
#print next(ll_iter) #It will throw StopIteration

print '###########'
ll_iter = ll.__iter__()

while True:
try:
item = next(ll_iter)
print item
#except StopIteration:
# print e
# break
except Exception,e:
break

print '$$$$$$$$$$$$'
ll_iter = ll.__iter__()
for each in ll_iter:
print each

Output:
A
B
C
------
A
B
C
-------
[0, 1, 2, 3, 4]
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__length_hint__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'next']
<listiterator object at 0x03978190>
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__length_hint__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'next']
0
1
2
3
4
###########
0
1
2
3
4
$$$$$$$$$$$$
0
1
2
3

4

Jan 16, 2019

Python csv content to dictionary

import csv

file_name = 'student.csv'
input_file_handle = csv.DictReader(open(file_name, 'rb'))
for row in input_file_handle:
     print row  #This will print row as dictionary
     print row['id']
     print row['name']
     print row['email']



Jan 12, 2019

Python Operator Overloading

#Operator overloading
class operatorOverloadObject:
    def __init__(self, x = 0, y = 0):
        self.x = x
        self.y = y
    
    def __str__(self):
        return "({0},{1})".format(self.x,self.y)
    
    def __add__(self,other): #Fucntion to overload + operator
        x = self.x + other.x
        y = self.y + other.y
        return operatorOverloadObject(x,y)

obj1 = operatorOverloadObject(1, 2)
obj2 = operatorOverloadObject(3, 4)
print(obj1)  #(1,2)
print(obj2)  #(3,4)
print(obj1 + obj2)  #(4,6) 

#Other operations to overload...
#Addition    p1 + p2, p1.__add__(p2)
#Subtraction p1 - p2, p1.__sub__(p2)
#Multiplication  p1 * p2, p1.__mul__(p2)
#Power   p1 ** p2,    p1.__pow__(p2)
#Division    p1 / p2, p1.__truediv__(p2)
#Floor Division  p1 // p2,    p1.__floordiv__(p2)
#Remainder (modulo)  p1 % p2, p1.__mod__(p2)
#Bitwise Left Shift  p1 << p2,    p1.__lshift__(p2)
#Bitwise Right Shift p1 >> p2,    p1.__rshift__(p2)
#Bitwise AND p1 & p2, p1.__and__(p2)
#Bitwise OR  p1 | p2, p1.__or__(p2)
#Bitwise XOR p1 ^ p2, p1.__xor__(p2)
#Bitwise NOT ~p1, p1.__invert__()

Jan 11, 2019

Python Class methods static vs class

#class method demo
class Pets:
    name = "pet animals"

    @classmethod
    def about(cls):
        print("This class is about {}!".format(cls.name))
    
class Dogs(Pets):
    name = "'man's best friends'"

class Cats(Pets):
    name = "cats"

p = Pets() #parent class
p.about() #This class is about pet animals!

d = Dogs() #inherited class
d.about() #This class is about 'man's best friends'!

c = Cats() #inherited class
c.about() #This class is about cats!


#static method demo
class Pets:
    name = "pet animals"

    @staticmethod
    def about():
        print("This class is about {}!".format(Pets.name))   
    
class Dogs(Pets):
    name = "'man's best friends'"

class Cats(Pets):
    name = "cats"

p = Pets()
p.about() #This class is about pet animals!
d = Dogs() 
d.about() #This class is about pet animals!
c = Cats()
c.about() #This class is about pet animals!


Python encapsulation getter setter

#Python OOPS Getter / Setter
class Person(object):
    def __init__(self, p_name=None):
        self._name = p_name

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, new_name):
        if type(new_name) == str: #type checking for name property
            self._name = new_name
        else:
        print 'Error: Invalid type to set'

    @name.deleter
    def name(self):
        del self._name

print '############# Getter/Setter'
p = Person('Mike')
print(p.name)  #Mike
p.name = 'George'  #Grorge
print(p.name)
p.name = 2.3 # Causes an exception, Error: Invalid type to set
print(p.__dict__)  #{'_name': 'George'}
del p.name
print(p.__dict__) #{}

Python Inheritance Detail

#Multiple inheritance
class Base1:
    @classmethod
    def f1(self):
    print  'Base1 f1'
    def f2(self):
    print  'Base1 f2'   

class Base2:
    def f1(self):
    print  'Base2 f1'
    def f2(self):
    print  'Base2 f2'
    def f3(self):
    print  'Base2 f3'   

class MultiDerived(Base1, Base2):
    def f1(self):
    print  'MultiDerived f1'

print '###########Multiple inheritance'
md = MultiDerived()
md.f1()  #MultiDerived f1
md.f2()  #Base1 f2
md.f3()  #Base2 f3
Base1.f1()  #Base1 f1  #classmethod
#Base2.f1()  #fail
#MultiDerived.f1()  #fail


#Multi-level inheritance
class Base:
    def f1(self):
    print  'Base f1'

class Derived1(Base):
    def f1(self):
    print  'Derived1 f1'
    def f2(self):
    print  'Derived1 f2'

class Derived2(Derived1):
    pass

print '###########Multi-level inheritance'
d2 = Derived2()
d2.f1() #Derived1 f1
d2.f2() #Derived1 f2      

Python csv

import io
import csv

output = io.BytesIO()
writer = csv.writer(output)

row = ['Name', 'City', 'Phone']
writer.writerow(row)
row1 = ['test1', 'city1', '123456789']
writer.writerow(row1)
row2 = ['test2', 'city2', '234567890']
writer.writerow(row2)
data =  output.getvalue()
fname = "output2.csv"
f = open(fname, 'wb')
f.write(data)
f.close()

Jan 8, 2019

Python Thread Functions

import time
import threading
from threading import Thread

def sleepFunc(i):
    print("Thread %s going to sleep for 5 seconds..." % threading.current_thread())
    time.sleep(5)
    print("Thread %i is awake now..." % i)


for i in range(10):
    th = Thread(target=sleepFunc, args=(i, ))
    th.start()
    print("Current Threads count: %i." % threading.active_count())


for thread in threading.enumerate():
    print("Thread name is %s ..." % thread.getName())

Python Thread concepts

from threading import Thread
import time

class abc(Thread):
def run(self):
for i in range(5):
print 'abc'
time.sleep(1)

class xyz(Thread):
def run(self):
for i in range(5):
print 'xyz'
time.sleep(1)

a = abc()
b = xyz()
a.start()
time.sleep(0.2)
b.start()

a.join()
b.join()

print 'bye'

Python copy file

#copy txt file
rf = open('input.txt', 'r')
wf = open('output.txt', 'w')

for i in rf:
    wf.write(i)


#copy image - binary
rf = open('relax.jpg', 'rb')
wf = open('relax1.jpg', 'wb')

for i in rf:
    wf.write(i)

Python anagram puzzle

An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
E.g., Fried, Fired


def is_anagram(s1, s2):
print (f'{s1}, {s2}')
s1 = s1.replace(' ', '')
s2 = s2.replace(' ', '')
return sorted(s1) == sorted(s2)


print(is_anagram('silent', 'listen'))                                 # True
print(is_anagram('public relations', 'crap built on lies'))   # True




Dec 8, 2018

Python Sparkpost sample

How to send emails from Python using Sparkpost module


In this tutorial, we will see how to send emails using Sparkpost.

First you need to register with Sparkpost and get your API key, so that you can use this key in sending e-mails.

The advantage/beauty of using sparkpost module is

  • You can send thousands of emails even in the free-tier.
  • You can send attachments & you can use html.
  • You can schedule the emails for future date & time.
  • You can also delete the future emails if not required.
  • It has lot more flexible features than inbuilt smtplib.
  • You can check the delivery status of your emails in Sparkpost dashboard (once you login, you can able to see this)
  • Python API is very simple to use, they also support their APIs in multiple languages.


from sparkpost import SparkPost

emails_to_send = ['test@gmail.com']
sp = SparkPost('XXXXXXXXXXXXXXXXXXXXXXXX') #Key

response = sp.transmissions.send(
          recipients=emails_to_send,
          html='',
          from_email='noreply@test.com',
          subject='test'
)
print(response)


Sep 5, 2018

Boto - Uploading file to a specific location on Amazon S3

When I upload a file from my local system to S3
  • Say media/downloads/logo.png it writes to <bucket>/media/downloads/logo.png
  • Suppose if I want to write to <bucket>/logo.png instead of media/downloads, please find the below script

import subprocess
import mimetypes
from boto.s3.connection import S3Connection, Location
from boto.s3.key import Key
import boto
import os

S3_BUCKET = ''

S3_KEY = ''
S3_SECRET = ''
conn = S3Connection(S3_KEY, S3_SECRET, calling_format=boto.s3.connection.OrdinaryCallingFormat())
bucket = conn.get_bucket(S3_BUCKET)
print bucket

key_name = 'logo.png'
path = 'media/img/'
full_key_name = os.path.join(path, key_name)
new_key = Key(bucket)
new_key.key = 'logo.png'
ctype = mimetypes.guess_type(full_key_name)[0] or "application/x-octet-stream"
new_key.set_metadata('Content-Type', ctype)
new_key.set_contents_from_filename(full_key_name)
if new_key.exists() == True:
   bucket.set_acl("public-read",new_key.key)
   url = new_key.generate_url(0, 'GET', None, False)
   print url



Thanks for reading.


Sep 2, 2018

How can you terminate custom/external HTTPS SSL certificate in AWS ELB and EC2

How can you terminate custom/external HTTPS SSL certificate in AWS ELB & EC2?
    1) at ELB level
        use AWS certificate manager, create a certificate & upload your existing certificate
        In ELB Listener rules, configure HTTPS(443 port) & attach the above certificate
        Limitation: You can add only one certificate per an ELB
    2) at EC2 level
        Suppose if you have multiple sites under EC2 (multi-tenant) & want to terminate HTTPS certificates for all the sites
        Having an ELB for each site will be costly solution, then you need to use TCP pass through solution
            https://test1.com
            https://test2.com
            https://test2.com
        In ELB Listener rules, configure TCP (443 port) pass through
        You could not obtain the clients IP address if the ELB was configured for TCP load balancing, so enable proxy protocol
        Enable proxy protocol in ELB through CLI (not available in AWS console), which allows X-Forwarded-For headers  
        Then the termination happens at you EC2 server level (Nginx/Apache)
       
        Nginx:
            server {
              listen *:443 ssl proxy_protocol;
              server_name *.site.com;
              set_real_ip_from 0.0.0.0/0;
              real_ip_header proxy_protocol;

              ssl on;
              ssl_certificate /opt/site/conf/ssl_keys/nginx_site.crt;
              ssl_certificate_key /opt/site/conf/ssl_keys/site.pem;

              location / {
                proxy_pass            http://127.0.0.1:80;
                proxy_read_timeout    90;
                proxy_connect_timeout 90;
                proxy_redirect        off;

                proxy_set_header      X-Real-IP $proxy_protocol_addr;
                proxy_set_header      X-Forwarded-For $proxy_protocol_addr;
                proxy_set_header      X-Forwarded-Proto https;
                proxy_set_header      X-Forwarded-Port 443;
                proxy_set_header      Host $host;
                proxy_set_header      X-Custom-Header nginx;
              }
            }

Sep 1, 2018

S3 Direct Upload Python Django

Using Pyhton Boto API, we can interact with Amazon S3 servers (for GET, PUT, POST etc)
We can also directly upload files to Amazon S3 from the client browser using Browser Uploads to S3 using HTML POST Forms.

Ref:
https://aws.amazon.com/articles/Java/1434

Prerequisites:
S3_BUCKET
S3_KEY
S3_SECRET
S3_URL

Note:
As per Amazon API, we need to encode policy format to base64 and further generate signature with SHA1
Both Policy and Signature need to be posted
Expiration : You can define the expiration time
acl: public-read/private
$key: upload path startes with
Check the POST S3 Url in HTML
Once the document is successfully uploaded to S3, S3 URL is shown on the page

Django Pyhton View:

import base64
import hmac, hashlib
import re

def direct_s3_upload(request):
  my_bucket = None
  policy_document = None
  policy_base_64 = signature = cors_xml = ""
  try:
    policy_document = '{"expiration": "2020-01-01T00:00:00Z", \
                       "conditions": [ \
                         {"bucket": "%s"}, \
                         {"acl": "public-read"}, \
                         ["starts-with", "$key", "uploads/"], \
                         ["content-length-range", 0, 524288000] \
                       ] \
                    }' % (<S3_BUCKET>)

    whitespace = re.compile(r'\s+')
    policy_document = whitespace.sub('', policy_document)
    policy_base_64 = base64.b64encode(whitespace.sub('', policy_document))
    signature = base64.b64encode(hmac.new(S3_SECRET, policy_base_64, hashlib.sha1).digest()) 
    dic1 = { 
           'MY_BUCKET_NAME': <S3_BUCKET>,
           'MY_AWS_KEY_ID': <S3_KEY>, 
           'MY_POLICY' : policy_base_64,
           'MY_SIGNATURE' : signature,
        }
  except:
    write_exception("direct_s3_upload")
  return render_to_response('test_s3_upload.html', context_instance=RequestContext(request, dic1))


HTML:  (test_s3_upload.html)
<html> 
  <head>
    <title>S3 POST Form</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <script>
      var bucketName = '{{MY_BUCKET_NAME}}';
      var AWSKeyId   = '{{MY_AWS_KEY_ID}}';
      var policy     = '{{MY_POLICY}}';
      var signature  = '{{MY_SIGNATURE}}';

      function S3ToolsClass() {
        var _handle_progress = null;
        var _handle_success  = null;
        var _handle_error    = null;
        var _file_name       = null;

        this.uploadFile = function(file, progress, success, error) {
          _handle_progress = progress;
          _handle_success  = success;
          _handle_error    = error;
          _file_name       = file.name;

          console.log(file.name)
          var fd = new FormData();
          fd.append('key', "uploads/" + file.name);
          fd.append('AWSAccessKeyId', AWSKeyId);
          fd.append('acl', 'public-read');
          fd.append('policy', policy);
          fd.append('signature', signature);
          fd.append("file",file);

          var xhr = new XMLHttpRequest({mozSystem: true});
          xhr.upload.addEventListener("progress", uploadProgress, false);
          xhr.addEventListener("load", uploadComplete, false);
          xhr.addEventListener("error", uploadFailed, false);
          xhr.addEventListener("abort", uploadCanceled, false);
          xhr.open('POST', 'https://s3.amazonaws.com/' + bucketName + '/');

          xhr.send(fd);
        }

        function uploadProgress(evt) {
          if (evt.lengthComputable) {
            var percentComplete = Math.round(evt.loaded * 100 / evt.total);
            _handle_progress(percentComplete);
          }
        }

        function uploadComplete(evt) {
          if (evt.target.responseText == "") {
            console.log("Upload complete - success") 
            _handle_success(_file_name);
          } else {
            console.log("Upload complete - not success") 
            _handle_error(evt.target.responseText);
          }
        }

        function uploadFailed(evt) {
          console.log("upload Failed")
          _handle_error("There was an error attempting to upload the file." + evt);
        }

        function uploadCanceled(evt) {
          console.log("upload cancelled")
          _handle_error("The upload has been canceled by the user or the browser dropped the connection.");
        }
      }
      var S3Tools = new S3ToolsClass();
      
      function uploadFile() {
        var file = document.getElementById('file').files[0];
        S3Tools.uploadFile(file, handleProgress, handleSuccess, handleError);
      }

      function handleProgress(percentComplete) {
        document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
      }

      function handleSuccess(fileName) {
        document.getElementById('progressNumber').innerHTML = 'Done!';
        document.getElementById('resultant_s3_url').innerHTML = 'https://s3.amazonaws.com/' + bucketName + '/uploads/' + fileName;
      }

      function handleError(message) {
        document.getElementById('progressNumber').innerHTML = 'Error: ' + message;
      }
    </script>
  </head>
  <body>
    <form id="form" enctype="multipart/form-data" method="post">
      <div class="row">
        1. Select a File<br>
        <input type="file" name="file" id="file"/>
      </div>
      <br>
      <div class="row">
        2. Upload File<br>
        <input type="button" onclick="uploadFile()" value="Upload" />
        <br/>
        <span id="progressNumber"></span>
      </div>
    </div>
    <br>
    <div class="row">
      3. Result S3 Url
      <br>
      <div id="resultant_s3_url"> </div>

    </div>
  </body>
</html>
Thank you for reading this article.

Aug 31, 2018

AWS S3 Bucket action doesn't apply to any resources

I am trying to add a bucket policy to avoid bucket deletion & avoid deletion of objects in the bucket as well.

So I need to add a bucket policy to achieve my requirement mentioned above.

The following bucket policy giving error like
'Action does not apply to any resource(s) in statement'
{
  "Id": "Policy1527043264306",
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1527043262106",
      "Action": [
        "s3:DeleteBucket",
        "s3:DeleteBucketPolicy",
        "s3:DeleteObject"
      ],
      "Effect": "Deny",
      "Resource": "arn:aws:s3:::prabhath-delete1",
      "Principal": {
        "AWS": [
          "XXXXXXXX"
        ]
      }
    }
  ]
}

We will discuss what caused the issue & how to resolve this.

Reason:

The following will apply on the bucket level only, so you need to define Resource as arn:aws:s3:::prabhath-delete-test
s3:DeleteBucket
s3:DeleteBucketPolicy

The following will apply on the bucket object level, so you need to define Resource as arn:aws:s3:::prabhath-delete-test/*
s3:DeleteObject

Solution:
You need to create two statements to cater the different types of actions as mentioned below:
One statement defines the following

  • s3:DeleteBucket
  • s3:DeleteBucketPolicy

Another statement defines the following
  • s3:DeleteBucketPolicy
 Correct version of bucket policy looks like below:

{
    "Version": "2012-10-17",
    "Id": "Policy1526996283460",
    "Statement": [
        {
            "Sid": "Stmt1526996142070",
            "Effect": "Deny",
            "Principal": {
                "AWS": "arn:aws:iam::XXXXXXX:root"
            },
            "Action": [
                "s3:DeleteBucket",
                "s3:DeleteBucketPolicy"
            ],
            "Resource": "arn:aws:s3:::prabhath-delete-test"
        },
        {
            "Sid": "Stmt1526996279916",
            "Effect": "Deny",
            "Principal": {
                "AWS": "arn:aws:iam::XXXXXXXXX:root"
            },
            "Action": "s3:DeleteObject",
            "Resource": "arn:aws:s3:::prabhath-delete-test/*"
        }
    ]
}

Jul 2, 2018

Python Operators

#!/usr/local/bin/python2.7

'''
    #Learning variables in Python
    File name: python_operators.py
    Author: Prabhath Kota
    Date: June 29, 2018
    Python Version: 2.7
'''

'''
Python Arithmetic Operators: +, -, *, /, % (modulus), ** (exponent), // (Floor Division)
Python Comparison Operators: ==, !=, <> (not equals), >, <, >=, <=
Python Assignment Operators: =, +=, -=, *=, /=, %=, //=
Logical: and, or, not
Python Identity Operators: Identity operators compare the memory locations of two objects  
Python Operators Precedence: 
Exponentiation (raise to the power)
Multiply, divide, modulo and floor division
Addition and subtraction
Comparison operators
Equality operators
'''

a = 100
b = 200
c = 10
print '-----------------Python Arithmetic Operators-----------------'
print a+b #300
print a-b #-100
print a*b #20000
print b/a #2
print b%a #0
print b**a #....
print '-----------------Python Comparision Operators-----------------'
print a == b #False
print a>b #False
print a != b #True
print a<>b #True #Not equals to
print a>b #False
print a < b #True
print '-----------------Python Assignment Operators-----------------'
b += 100
print b
b *= 10
print b
b  = 200
b %= 10
print b
print '-----------------Python Membership Operators-----------------'
print 10 in [100, 200, 10, 300]
print 111 not in [100, 200, 10, 300]

print '-----------------Python Operators Precedence-----------------'
a = 20
b = 10
c = 15
d = 5
e = 0

e = (a + b) * c / d       #( 30 * 15 ) / 5
print "Value of (a + b) * c / d is ",  e

e = ((a + b) * c) / d     # (30 * 15 ) / 5
print "Value of ((a + b) * c) / d is ",  e

e = (a + b) * (c / d);    # (30) * (15/5)
print "Value of (a + b) * (c / d) is ",  e

e = a + (b * c) / d;      #  20 + (150/5)
print "Value of a + (b * c) / d is ",  e


Learning control flow statements in Python

#!/usr/local/bin/python2.7

'''
    #Learning control flow statements in Python
    File name: python_control_flow_statements.py
    Author: Prabhath Kota
    Date: June 29, 2018
    Python Version: 2.7
'''

'''
Sequential
Selection (Python Conditional Statements) 
if
if...else
if..elif..else statements
nested if statements
not operator in if statement
and operator in if statement
in operator in if statement
Repetetion
for loop
while loop
'''

print('-------------------Python if statements----------------')
x=20
y=10
if x > y :
  print("X is bigger")
#X is bigger

print('-------------------Python if...else statements----------------')
x=10
y=20
if x > y :
  print("X is bigger")
else :
  print("Y is bigger")
#Y is bigger

print('-------------------Python if...else...else statements----------------') 
x=500
if x > 500 :
  print("X is greater than 500")
elif x < 500 :
  print("X is less than 500")
elif x == 500 :
  print("X is 500")
else :
  print("X is not a number")
#X is 500

print('-------------------Python Nested if statements----------------') 
mark = 72
if mark > 50:
  if mark >= 80:
    print ("You got A Grade !!")
  elif mark >= 60 and mark < 80 :
    print ("You got B Grade !!")
  else:
    print ("You got C Grade !!")
else:
  print("You failed!!")
#You got B Grade !!

print('-------------------not operator in if statement----------------') 
mark = 100
if mark != 100: #mark != 100
  print("mark is not 100")
else:
  print("mark is 100")
#mark is 100

print('-------------------and operator in if statement----------------') 
mark = 72
if mark > 80:
  print ("You got A Grade !!")
elif mark >= 60 and mark < 80 :
  print ("You got B Grade !!")
elif mark >= 50 and mark < 60 :
  print ("You got C Grade !!")
else:
  print("You failed!!")
#You got B Grade !!

print('-------------------in operator in if statement----------------') 
color = ['Red','Blue','Green']
selColor = "Red"
if selColor in color:
  print("Red is in the list")
else:
  print("Not in the list")
#Red is in the list4

print '----------------For loop---------------------'
freedom_fighters = ["Lala Lajipati Rai", "Dadabhai Naoroji", "Rajendra Prasad", "Sarojini Naidu", "Dadabhai Naoroji", "Lal Bahadur Shastri"]
print freedom_fighters
for each in freedom_fighters:
print each

#['Lala Lajipati Rai', 'Dadabhai Naoroji', 'Rajendra Prasad', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Lal Bahadur Shastri']
#Lala Lajipati Rai
#Dadabhai Naoroji
#Rajendra Prasad
#Sarojini Naidu
#Dadabhai Naoroji
#Lal Bahadur Shastri

print '----------------While loop---------------'
#Try to avoild While loops, use only unless otherwise reequired
#If you sometimes don't handle it, it may end up in infinite loop
i = 0
squares = []
while(i < 10):
squares.append(i**2)
i += 1
print squares
#[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Jul 1, 2018

Learning variables in Python

#!/usr/local/bin/python2.7

'''
    #Learning variables in Python
    File name: python_variables.py
    Author: Prabhath Kota
    Date: June 29, 2018
    Python Version: 2.7
'''

'''
Unlike other programming languages, Python there is no need to declare a variable.
A variable is created when you first assign a value to it.
A variable can have a short or uder understandbale name

Rules for Python variables:
A variable name cannot start with a number
Variable names are case-sensitive (height, Height and HEIGHT are three different)
A variable name must start with a letter or the underscore character
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
'''

var_a = 100
print var_a
#100

var_a = 'Hi'
print var_a
#Hi

#1_var = 'Hi'
#wrong declaration

#Case-Sensitive
height = 5.0
print height

Height = 5.2
print Height

HEIGHT = 5.6
print HEIGHT