Python Getting Started : #2 Functions

This is the second in the queue which will be covering python functions in short.

Functions

A function is a named sequence of statements that performs a computation. one can call the function by its name.

>>> type('ABC')

<type 'str'>

Here the name of the function is type and expression in parenthesis is called the arguments of the function.

Type Conversion Functions

Various methods in python are used to convert values from one type to another like int, float, str, etc.

>>> int('40')

40

>>> int(11.99)

11

>>> float('3')

3.0

>>> str(40)

'40'

>>> str(3)

'3'

As it can be seen int function converts a float number to integers, instead of rounding it ignores the fractional part.

Math Functions

Python has a math module which consists most of the mathematical functions. A module is a file that contains a collection of functions. Before using any module, it has to be imported.

>>> import math

>>> print math

<module 'math' (built-in)>

import math statement creates a moduled object named math which has been printed above in second statement. This module object is the reference to the variables and functions defined in module. To access variable or function by module object, module object and function/variable name to be specified separated by a dot.

>>> 20 * math.pi

62.83185307179586

Expression math.pi is used to get the variable pi from math module.

Adding New Functions

>>> def new_function():

...         print 'I am in newly created new_function'

...

The name of the new function and sequence of statements form a function definition, this sequence of statements are executed when function is called. def is a python keyword which indicates to interpreter that this is a function definition. Rules for function names is same as for variables. You should avoid variable and function name as same. The first line of the function is called the header, rest is called body. The header has to be end with a colon and the body has to be indented. By convention indentation is to be always 4 spaces.

If a function definition is typed in an interactive mode, interpreter print ellipses(...) to let you know that definition is not complete, here to end the function you have to enter an empty line.

Defining a function creates a variable with same name.

>>> print new_function

<function new_function at 0xb79e7ee9c>

>>> type(new_function)

<type 'function'>

A defined function can be used inside other functions.

>>> def second_function():

...         print 'In second function'

...         new_function()

...

>>>  print second_function()

In second function

print 'I am in newly created new_function'

Remember you have to create a function before executing it means function definition is to be executed before the function is called the first time.

Flow of Execution

Order in which statements are executed is known as flow of execution. Execution always begins at the first statement. Statements are always executed once at a time, in order from top to bottom.

Function definitions does not affects the flow of execution as statements in the function definition are executed when that function is called.

When a function is called then control goes to body of that function and after executing all statements of called function it returns back where it left off. A function can be called from another function which may be called from some other function and so on, but we need not to worry as python is cool in tracking this. 

Parameter And Arguments

Inside a function, arguments are assigned to variables called parameters. The argument is evaluated before the function is called. Variables and parameters created in function are local, which means their scope is till that function only.

>>> str1 = 'First String'

>>> str2 = 'Second String'

>>> def add(var1, var2):

...         result = var1+var2

...

>>> print result

NameError: name 'result' is not defined

Void Functions

Functions which do not return any value when called are known as void functions. If you try to assign the result of the void function to a variable, you will get a special value called None. The value None is not same as string 'None', It is a sepacil value that has its own type.

>>> output = add('string1', 'string2')

>>> print output

None

>>> print type(ouput)

<type 'NoneType'>

Why to use functions

- Easy to debug in a program

- Can be reused.

- Eleminates a repititive code.

Importing with from

There are 2 ways to import modules. One already used above i.e import math, other is:

>>> from math import pi

>>> print pi

3.14159265359

Now as you can see, you can access pi variable of math module directly without module name and dot notation. You can use * operator to import everything from module.

>>> from math import *

>>> cos(pi)

-1.0

Python Getting Started : #1 Variables And Other Basic Topics

I am just starting with basics of python and assure you to cover most of the stuff on python in the other blogs.

Values And Type

A value is one of the basic things of a program like an alphabetical character or number('A', 'b', 2, 50). These values belongs to different types which can be figured out from interpreter also.

    >>> type('Python')

    <type 'str'>

    >>> type(100)

    <type 'int'>

    >>> type(2.20)

    <type 'float'>

    >>> type('5.5')

    <type 'string'>

You can notice that in the last one 5.5 is an integer but interpreter shows its of type string because yes anything under quotes is string.

Variables

A variable is a name that refers to a value. An assignment statement creates a new variable and gives them values.

>>> message = 'This is first in the list'

In the above statement, message is a variable whose value is a string \[code\]This is first in the list\[/code\]

Variable Names And Keywords

Variable names can consist of a combination of alphabets, numbers and a speacial symbol underscore(_) but it has to always start from an alphabet.

Keywords are reserved words in any of the language which have predefined meanings. you cannot use these words as a variable. Python 2 has 31 keywords.

>>> 23Var = 'Wrong'

SyntaxError: invalid syntax

>>> var$ = 1000

SyntaxError: invalid syntax

>>> print = 'Wrong'

SyntaxError: invalid syntax

First two gives error as we can see one starts with a number 23 and another consists of special symbol other than underscore. Last one gives as print is a keyword in python, so it cannot be used as a variable. Keynote is Keywords can never be used as variables.

Operator and Operands

Operators are special symbols that represents computations like addition, subtraction, etc. Operators are applied on the values called operands. The operators +, - , *, /, ** performs addition, subtraction, multiplication, divide and exponentiation. In many languages ^ is used for exponentiation while ** is used as XOR(Bitwise operator) but in python its vice versa. In python 2, divide operator has a trick hidden in it i.e it does floor division.

>>> 29/40

0

>>> 29/40.0

0.725

>>> 29.0/40

0.725

>>> 29.0/40.0

0.725

29/40 gives output as 0 instead of 0.725 but if either of the operand is  of type float, python does floating point division.

Order Of Operators

With more than one operator in an expression, order of execution depends on the rules of precedence. PEMDAS is a useful way to remember rules. P stands for parenthesis which executes first, than exponentiation, than Multiplication and division are in the same level executed on the basis of order of appearance from left to right, than addition and subtraction is at last in order.

String Operations

The + operator works with string as concatenation operator to join strings. The * operator also works on strings to perform repetition.

>>> 'First string' + 'Second String'

'First stringSecond String'

>>> 'First' * 5

'FirstFirstFirstFirstFirst'

Comments

Comments are the texts which can be added to a program just to describe the flow or any other message, basically these are those statements , expression, anything which are not executed by interpreter. One can add a comment at the start of the line or after the statement. The symbol to represent comments in python is #.

I hope now you are good to start with python functions, my next blog on python.