MP 1 Arsd Lecture 5
MP 1 Arsd Lecture 5
10-Sept-2024
on
“Functions”
Mathematical Physics -1
by
Prof. Vinita Tuli
Prof. Anjali Kaushik
Shivnandi
Sneh
Functions Basics
TRY IT! Verify that len is a built-in function using the type function.
type(len)
builtin_function_or_method
Functions Basics
TRY IT! Verify that np.linspace is a function using the type function.
And find how to use the function using the question mark.
import numpy as np
type(np.linspace)
function
Functions Basics
TRY IT! Verify that np.linspace is a function using the type function.
And find how to use the function using the question mark.
np.linspace? # this will work with jupyter notebook
Define your own function
TRY IT! We can define our own functions. A function can be specified in several ways. Here we will
introduce the most common way to define a function which can be specified using the keyword def, as
showing in the following:
def function_name(argument_1, argument_2, ...):
'''
Descriptive String
'''
# comments about the statements
function_statements
return out
Functions Basics
TRY IT! Define a function named my_adder to take in 3 numbers
and sum them.
def my_adder(a, b, c):
"""
function to sum the 3 numbers
Input: 3 numbers a, b, c
Output: the sum of a, b, and c
author:
date:
"""
# this is the summation
out = a + b + c
return out
d = my_adder(1, 2, 3)
print(d)
Local and Global variable
TRY IT!
x = "global"
def my_func():
x = "local"
print("Inside function:", x)
my_func()
print("Outside function:", x)
Passing Functions as Arguments
TRY IT! In Python, functions are first-class objects, meaning they can be
passed as arguments to other functions.
def add(a, b):
return a + b
result = apply_operation(add, 5, 3)
print("Result:", result)
Modules and Importing Modules
import math
print(math.sqrt(16))
Creating and Importing Your Own Module
TRY IT! To create a module, save a .py file with functions and
variables.
Import your module using import module_name.
# mymodule.py
def square(x):
return x ** 2
# main.py
import mymodule
print(mymodule.square(4)) # Outputs 16
Generating Pseudo-Random Numbers
import random
print("Random integer:", random.randint(1, 10))
print("Random float:", random.random())
Finding the Largest of Three Numbers
TRY IT!
def largest(a, b, c):
return max(a, b, c)
print(largest(5, 9, 3))
Listing Prime Numbers
TRY IT!
Write your own code to print prime number between 3 to 100?