A function is a block of organized, reusable code that is used to perform a single, related action. We know some built-in functions in Python like print() etc. You can also create your own functions. These functions are called user-defined functions.
Try the example:
def square1(int): k=int*int print 'square of enterd value is' return k
Now, save it into a file and run the Python script
Now try the following code to find mean of a set of numbers:
def mean(*input): sum = 0.0 myList = [] for char in input: myList.append(char) for num in input: sum += num mean = sum / len(myList) print 'The average of the given numbers is', mean
Here we used *input to pass all the parameters for calculating the mean of a set of numbers. This will enable to pass the set of numbers for which mean is to be calculated. For example, mean (12, 12, 13, 14, 14, 15, 11, 16) will give output ‘The average of the elements is 13.375’.
Even though you never wish to, but many times, errors creep into your program. So it is necessary to learn how to handle errors in Python. Now let us see some common errors, and how to handle the unexpected errors.
Have a look at the following code:
The first line in the error message indicates the details about the error. These built-in exceptions and comments are useful to understand about the error happened. An exception is a Python object that represents an error which helps the user or programmer, when there is some error in the block of program, which interrupts the flow of the program. It is possible to write user-defined exceptions and error handling. This is very essential in more serious programming.
The famous error handling method is try and except block. If you are not sure about a block of statements, or smell some error, you can put that block of statements inside try block. After try block, except block is used to incorporate exceptions.
Try the following code:
while True: try: x=int(raw_input("Please enter your age: ")) break except ValueError: print "please enter an integer, age cannot be an alphabet "
Here we used while loop to repeat the action till you enter an integer value. You can also use except statement without specifying the error. The code that needs to be run anyway can be included in the finally block. The codes written in this block will always run. Try the following code:
a = input("Please numerator (a=):") b = input("Please denominator (b=):") try: result = a/b except ZeroDivisionError: print "division by zero is not possible!" except TypeError: print "Enter two integers, one of it is a string" else: print "result is", result finally: print "This is finally clause, this will run always"
Python supports the creation of anonymous functions (i.e. functions that are not bound to a name) at runtime, using a construct called lambda.
>>>def f(x, y, z): return x + y + z
>>>f(1,2,3)
>>>g = lambda x, y, z: x + y + z
>>>g(1,2,3)
__name__ == '__main__'
When you execute a Python script, it is treated as the main and its __name__ attribute is set to "__main__". If you import this script as a module in another script, the __name__ is set to the name of the script/module.
This is entry point for a code.
Create the following files.
# a.pyimport b
and
# b.pyprint "Hello World from %s!" % __name__ if __name__ == '__main__': print "Hello World again from %s!" % __name__
Running them will get you this output:
$ python a.py Hello World from b!
As you can see, when a module is imported, Python sets globals()['__name__'] in this module to the module's name.
$ python b.py Hello World from __main__!Hello World again from __main__!
As you can see, when a file is executed, Python sets globals()['__name__'] in this file to "__main__".
------------------------------------