Friday, July 6, 2012

Check the year is Leap year or not in Python

open a python script editor and just paste the following code in your new python(.py or .pyw) file -

def verifyLeapYear ():
    year = 2016
    print year
    if (year % 4 == 0) & (year % 100 != 0) | (year % 400 == 0):
        print "The " + str(year) + " is a Leap Year"
    else:
        print "The " + str(year) + " is not a Leap Year"
   
verifyLeapYear()


output is-

Reverse a String in Python

open a python script editor and just paste the following code in your new python(.py or .pyw) file -

def reverseString ():
    stringvalue = "String Reverse Function"
    print "\n"
    length = stringvalue.__len__()
    arr = ""
    for r in range(0,length):
        newchar = stringvalue[length -1 - r]
        arr += newchar
    print arr
   
reverseString()


output is-

You can do it same through a single line of command-
print 'String Reverse Function'[::-1]
Output is-

Generate a Fibonacci series in Python

open a python script editor and just paste the following code in your new python(.py or .pyw) file -

def fibonacciSeries ():
    previous = -1
    nextval = 1
    position =9
    for r in range(0,position):
        sum = nextval + previous
        previous = nextval
        nextval = sum
        print nextval

fibonacciSeries()


output is-

Create a Pyramid in Python

open a python script editor and just paste the following code in your new python(.py or .pyw) file -

def createPyramid ():
    minVal = 1
    maxVal = 35
    index = maxVal/2
    for r in xrange(minVal,maxVal,2):
        print " " * index + "*" * r
        index = index - 1
       
createPyramid()

output is-