Tuesday, July 14, 2015

Introduction to function - Python

Function - if you are familiar with any programming language, you should know what the function is. It is a process of minimizing code repetition. Of we have to do something frequently in a program we write the code snippet as function and call out when necessary.
Python function is declared by def and then followed by name of the function and parameters which the function needs, then followed by colon.
def add (a,b):
   c=a+b
   return c
while True:
   a=int(raw_input("please enter the first value or press x to quit"))
   b=int(raw_input("please enter the first value  or press x to quit"))
   if a=="x" or b=='x':
      break
   c=add(a,b)
   print c
  

Can you find the fault in the program? the a=='x' can not be executed as the conversion of x into integer can not be possible. So, the idle throws exception but also get out us of the loop.

you can also give default value to function input values. Lets see it.

def showname(name="Not Supplied",age=0):
    if name=="Not Supllied":
        print "Please supply the name"
        print "your age is =%d"%age
    elif age==0:
        print "Hello %s"%(name)
        print "You did not supplied the age, common don't be ashamed of your age"
    elif name=="Not Supplied" and age==0:
        print "Please supply the name and age"
    else:
        print "Hello",name," \n Your age is only ",age

while 1:
   
    name=raw_input("Press ctrl+c to quit. \nplease enter your name :")
    age =raw_input ("please enter your age :" )
    if name=="":
        showname(age)
    elif age=="":
        showname(name)
    elif age=="" and name=="":
        showname()
    else:
        showname(name,age)
   
This program contains some logical mistakes , can you identify them? if not see my blog about loops and conditionals.

  

No comments:

Post a Comment

Feautured Post

Python Trivia Post: enumerate()

Python has a very useful inbuilt function, which is called enumerate(). This is needed whenever you need the numbering of a certain element...