0% found this document useful (0 votes)
31 views

3 Functions

The document discusses Python functions including defining functions, return values, arguments, arbitrary arguments, keyword arguments, passing lists as arguments, function parameters, mean finding, classes and objects in Python.

Uploaded by

medsinofficial
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

3 Functions

The document discusses Python functions including defining functions, return values, arguments, arbitrary arguments, keyword arguments, passing lists as arguments, function parameters, mean finding, classes and objects in Python.

Uploaded by

medsinofficial
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

3_Functions file:///C:/Users/Shyam/AppData/Local/Temp/3_Functions.

html

TUTORIAL for Python Programming

Defining Functions
Defining functions use the def command.
Functions can have arguments and return values
Invoked by the name of the function

Simple Function Definition


In [ ]: def happy(): # There is a colon after function defin
ition
print("Happy Birthday to You!") # Function block is indented

Function Call

In [ ]: happy()

Happy Birthday to You!

Return Values
To let a function return a value, use the return statement:

In [ ]: def my_function(x):
return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))

15
25
45

Functions with arguments


In [ ]: # Example 1
def square(x): # x is here argument
y = x**2
return y

1 of 11 05-11-2020, 12:21
3_Functions file:///C:/Users/Shyam/AppData/Local/Temp/3_Functions.html

Function calling

In [ ]: x = 3;
w= square(x);
print("3x3 = ", w);
print (" 3 squared twice ", square(square(3)))
print (" In expression", 10+square(3))

3x3 = 9
3 squared twice 81
In expression 19

In [ ]: # Example 2
import numpy as np
def powers_any(x): # x is here argument
y= np.power(x,3)
return y

In [ ]: x = 3;
w= powers_any(x);
print("The power value is : = ", w);
print (" In expression", 10+powers_any(3))

The power value is : = 27


In expression 37

Function calling

In [ ]: # Example 2
def hbd(name):
print ("Happy Birthday to ", name)
return

Function calling

In [ ]: name = "shyam"
hbd(name)

Happy Birthday to shyam

2 of 11 05-11-2020, 12:21
3_Functions file:///C:/Users/Shyam/AppData/Local/Temp/3_Functions.html

Arbitrary Arguments, *args


If you do not know how many arguments that will be passed into your function, add a * before the
parameter name in the function definition.

This way the function will receive a tuple of arguments, and can access the items accordingly:

Example

If the number of arguments is unknown, add a * before the parameter name:

In [2]: def my_function(*kids):


print("The youngest child is ", kids[2])

my_function("Rohan", "Mohan", "Sohan")

The youngest child is Sohan

Keyword Arguments
You can also send arguments with the key = value syntax.

This way the order of the arguments does not matter.

In [3]: def my_function(child3, child2, child1):


print("The youngest child is " , child3)

my_function(child1 = "Rohan", child2 = "Mohan", child3 = "Sohan")

The youngest child is Sohan

Passing a List as an Argument


You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be
treated as the same data type inside the function.

E.g. if you send a List as an argument, it will still be a List when it reaches the function:

In [ ]: def my_function(food):
for x in food:
print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)

apple
banana
cherry

In [ ]:

3 of 11 05-11-2020, 12:21
3_Functions file:///C:/Users/Shyam/AppData/Local/Temp/3_Functions.html

Function Parameters
In [6]: import numpy as np
def addinterest(balance,rate):
balance = balance + np.multiply(balance , rate)
# print(balance)
# print(newbalance)
return balance

amounts= [200, 400]


print(amounts)
rate = 0.05
y=addinterest(amounts, rate)

print("Amounts after adding interest")


print(y)
print(" ID of Amount after adding Interest")
print(id(y))

[200, 400]
Amounts after adding interest
[210. 420.]
ID of Amount after adding Interest
2309572383408

Mean finding
In [ ]: import numpy as np
def mean(x):
b=np.sum(x)
y=b/len(x)
print(y)
return y

Calling function
In [ ]: a=np.arange(10)
z=mean(a)

4.5

Python Classes and Objects


Python is an object oriented programming language.
Almost everything in Python is an object, with its properties and methods.
A Class is like an object constructor, or a "blueprint" for creating objects.

https://docs.python.org/3/tutorial/classes.html (https://docs.python.org/3/tutorial/classes.html)

4 of 11 05-11-2020, 12:21
3_Functions file:///C:/Users/Shyam/AppData/Local/Temp/3_Functions.html

What is a class?
Classes are like a blueprint or a prototype that you can define to use to create objects.
A class is a code template for creating objects. Objects have member variables and have behaviour
associated with them. In python a class is created by the keyword class.

An object is created using the constructor of the class.

How to create a class


We define classes by using the class keyword, similar to how we define functions by using the def
keyword.
The simplest class can be created using the class keyword.

Example
Create a class named MyClass, with a property named x:

In [1]: class MyClass:


x = 10
y = 20

What is Object
An object is an instance of a class. This is the realized version of the class, where the class is manifested
in the program.

We can take the MyClass class defined above, and use it to create an object or instance of it.

Create Object
Now we can use the class named MyClass to create objects:

Example
Create an object named p1, and print the value of x:

In [2]: p1 = MyClass()
print(p1.x)
print(p1.y)

10
20

5 of 11 05-11-2020, 12:21
3_Functions file:///C:/Users/Shyam/AppData/Local/Temp/3_Functions.html

The pass Statement


class definitions cannot be empty, but if you for some reason have a class definition with no content, put in
the pass statement to avoid getting an error.
Example

In [4]: class Person:


pass

Example
In [5]: # Other Example
class Shark:
def swim(self):
print("The shark is swimming.")

def be_awesome(self):
print("The shark is being awesome.")

def main():
shyam = Shark()
shyam.swim()
shyam.be_awesome()

if __name__ == "__main__":
main()

The shark is swimming.


The shark is being awesome.

6 of 11 05-11-2020, 12:21
3_Functions file:///C:/Users/Shyam/AppData/Local/Temp/3_Functions.html

The Constructor Method: The__init__() Function


The constructor method is used to initialize data. It is run as soon as an object of a class is instantiated.
Also known as theinitmethod, it will be the first definition of a class.
To understand the meaning of classes we have to understand the built-ininit() function.
Class functions that begin with double underscoreare called special functions as they have special
meaning.
Of one particular interest is theinit__() function. This special function gets called whenever a new object
of that class is being initiated..
This type of function is also called constructors in Object Oriented Programming (OOP). We
normally use it to initialize all the variables.
The examples above are classes and objects in their simplest form, and are not really useful in
real life applications.

Use theinit() function to assign values to object properties, or other operations that are necessary to do
when the object is being created:
The__init__() function is called automatically every time the class is being used to create a new
object.
The simplest class can be created using the class keyword.

Example 1
Create a class named Person, use theinit() function to assign values for name and age:

In [13]: # Other Example


class Shark:
def __init__(self):
print("This is the constructor method.")
def swim(self):
print("The shark is swimming.")

def be_awesome(self):
print("The shark is being awesome.")

def main():
shyam = Shark()
shyam .swim()
shyam.be_awesome()

if __name__ == "__main__":
main()

This is the constructor method.


The shark is swimming.
The shark is being awesome.

7 of 11 05-11-2020, 12:21
3_Functions file:///C:/Users/Shyam/AppData/Local/Temp/3_Functions.html

Example 2
Create a class named Person, use theinit() function to assign values for name and age:

In [ ]: class Person:
def __init__(self, name, age):
self.name = name
self.age = age

# calling class function


p1 = Person("John", 36)
print(p1.name)
print(p1.age)

John
36

Secial Attributes
There are also special attributes in it that begins with double underscores. For exampledoc__gives us the
docstring of that class.

Example 3
Insert a function that prints a greeting, and execute it on the p1 object:

In [7]: class Person:


"This is a person class" # docstring of the class
def __init__(self, name, age):
self.name = name
self.age = age

# calling class function


p1 = Person("John", 36)
print(Person.__doc__)
print(p1.name)
print(p1.age)

This is a person class


John
36

Object Methods
Objects can also contain methods. Methods in objects are functions that belong to the object.

Let us create a method in the Person class:

8 of 11 05-11-2020, 12:21
3_Functions file:///C:/Users/Shyam/AppData/Local/Temp/3_Functions.html

In [ ]: class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def myfunc(self):
print("Hello my name is " + self.name)

#Calling class function


p1 = Person("John", 36)
p1.myfunc()

Hello my name is John

In [16]: # Alternate method


class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def myfunc(self):
print("Hello my name is " + self.name)

def main():
shyam = Person("John", 36)
shyam.myfunc()

if __name__ == "__main__":
main()

Hello my name is John

The self Parameter


The self parameter is a reference to the current instance of the class, and is used to access variables that
belongs to the class.

It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of
any function in the class:

Example
Use the words mysillyobject and abc instead of self:

9 of 11 05-11-2020, 12:21
3_Functions file:///C:/Users/Shyam/AppData/Local/Temp/3_Functions.html

In [ ]: class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age

def myfunc(abc):
print("Hello my name is " + abc.name)

#Calling class function


p1 = Person("John", 36)
p1.myfunc()

Hello my name is John

Modify Object Properties


You can modify properties on objects like this:

Example
Set the age of p1 to 50:

In [ ]: p1.age = 50
print(p1.age)

50

Delete Object Properties


You can delete properties on objects by using the del keyword:

Example
Delete the age property from the p1 object:

In [ ]: del p1.age

# print(p1.age)

Delete Objects
You can delete objects by using the del keyword:

10 of 11 05-11-2020, 12:21
3_Functions file:///C:/Users/Shyam/AppData/Local/Temp/3_Functions.html

Example
Delete the p1 object:

In [ ]: del p1

11 of 11 05-11-2020, 12:21

You might also like