Functions - Python: Programming Language for Beginners - Learn In A Day! (2015)

Python: Programming Language for Beginners - Learn In A Day! (2015)

Chapter 8. Functions

Definition:

Functions are little programs that perform a given task, which can be incorporated into our own larger codes. You can use the created function at any time and at any place. It saves a lot of your time and efforts of retelling the system what to do during each iteration.

Functions

Python has many inbuilt functions that can be used whenever needed i.e. simply by 'calling' them. 'Calling' a function means giving contribution to that function and it returns the output as the variable does.

Example -How to call a function

function_name(parameters)

Function_name determines what function you should use. Say, raw_input, is the first function that is used.

Parameters are known as the values that one passes to tell a function what it is supposed to do and how it should be done. Say, if any function is multiplied to any given integer say five, then the parameters will tell the function what number it will multiply by 5. Insert the number 70 within the parenthesis, and the function will multiply 70*5.

The function raw_input asks the user to type out anything and it will return a string.

Example - Using raw_input

a = raw_input ("Type in something, and it will be repeated on screen:")

print a

Function defined in your own way

Till now we have been using the inbuilt functions, however, what if we could create our own function and use it whenever and wherever we liked. The 'def' operator makes an entry here. (An operator just tells python what it has to do, e.g. the ‘+’ operator instructs python to add)

Example -The def operator

def function_name(parameter_1,parameter_2):

{this is the code in the function}

{more code}

{more code}

return {value to return to the main program}

{this code isn't in the function}

{because it isn't indented}

#remember to put a colon":"at the end

#of the line that starts with'def'

A function need not depend on the main program.

Passing Parameters of functions

Example - Defining functions using parameters

def function_name(parameter_1,parameter_2):

{this is the code in the function}

{more code}

{more code}

return {value (e.g. text or number) to return to the main program}

Ways to pass Parameters

Example -The results of fancy parameter work

add(5,40)

When an add program runs, adding the two numbers 5 and 40, followed by printing result. The add program doesn’t have a 'return' operator so it does not give back anything in the main program. It just adds the two numbers that are passed down as parameters. It then prints them on screen, and the main program doesn't know anything.

Instead of (input("Add this: "),input("to this: ")) you can have variables as parameters as well.

Example – Variables as parameters

num1 = 4

num2 = 2

addition(num1,num2)

In the above example, variables are being passed as parameters to function. It is possible to directly pass the values to the function:

Example - the end result

add(45,7)

The only thing function sees is value of a parameter being passed. These values then are put in the variables which are mentioned when 'add' is defined (the line 'def add(a,b)' ). The function then uses those parameters to carry out its task.

Now that you have an idea about the basics of python programming, let us go through a few simple python programs to make concepts clearer for you:

Matrix Multiplication using Nested Loop

Source Code

# Multiplication of two matrices using nested loops

# 3x3 matrix

X = [[12,7,3],

[4 ,5,6],

[7 ,8,9]]

# 3x4 matrix

Y = [[5,8,1,2],

[6,7,3,0],

[4,5,9,1]]

# result is 3x4

result = [[0,0,0,0],

[0,0,0,0],

[0,0,0,0]]

# iterate through rows of X

for i in range(len(X)):

# iterate through columns of Y

for j in range(len(Y[0])):

# iterate through rows of Y

for k in range(len(Y)):

result[i][j] += X[i][k] * Y[k][j]

for r in result:

print(r)

Output

[114, 160, 60, 27]

[74, 97, 73, 14]

[119, 157, 112, 23]

The above program uses nested for loops for iterating through each of the rows and columns. Then the sum of products is stored in the result.

Python program to check if a given number is prime or not:

A prime number is a positive integer which is greater than 1 and does not have any other factors except for 1 and itself. The examples of prime numbers are 2, 3, 5, 7 etc..

8 is not a prime number as it has the factors 2 and 4, apart from 1 and itself

# Python program to check if the input number is prime or not

# take input from the user

num = int(input("Enter a number: "))

# prime numbers are greater than 1

if num > 1:

# check for factors

for i in range(2,num):

if (num % i) == 0:

print(num,"is not a prime number")

print(i,"times",num//i,"is",num)

break

else:

print(num,"is a prime number")

# if input number is less than

# or equal to 1, it is not prime

else:

print(num,"is not a prime number")

Output 1

Enter a number: 407

407 is not a prime number

11 times 37 is 407

Output 2

Enter a number: 853

853 is a prime number

Python program to display the Fibonacci sequence:

A Fibonacci sequence is a sequence which starts from o and 1 and proceeds by adding two preceding terms to give rise to a new term. In other words, the nth term is obtained by adding (n-1)th and (n-2)th term. The sequence thus obtained is as follows: 0, 1, 1, 2, 3, 5, 8....

Source Code

# Python program to display the Fibonacci sequence up to n-th term using recursive functions

def recur_fibo(n):

"""Recursive function to

print Fibonacci sequence"""

if n <= 1:

return n

else:

return(recur_fibo(n-1) + recur_fibo(n-2))

# take input from the user

nterms = int(input("How many terms? "))

# check if the number of terms is valid

if nterms <= 0:

print("Plese enter a positive integer")

else:

print("Fibonacci sequence:")

for i in range(nterms):

print(recur_fibo(i))

Output

How many terms? 10

Fibonacci sequence:

0

1

1

2

3

5

8

13

21

34

Python program to check if a string is a palindrome or not

What is a Palindrome?

A palindrome is a string which when reversed remains the same . An example of a palindrome is the word ‘madam’. Reverse the word and you will still get the word ‘madam’. Words like ‘Sir’ are not palindromes. Reversing the word gives ‘riS’. Hence it is not a palindrome.

# Python program to check if a string is a palindrome or not

print "What is the word you would like to check?" # Asks the user what word they would like to check.

x = raw_input("> ") # User inputs the word.

y = x[::-1] # reverses the string.

if x.lower() == y.lower(): # checks if the strings match, this way it handles case sensitivity.

print x,"is a palindrome!" # prints it is a palindrome

else: # and if it's not a palindrome

print x,"is not a palindrome!" # it will print it is not a palindrome

Let us touch upon the concepts of tuples and dictionaries in the next chapter.