Intro
Here, we’ll discussed about:
1. Function in Python
- Self Defined vs Buitl-in functions
- Declearing and Calling a function
- Default Parameters
- Local & Global scope of variables
2. Modules in Python
- Creating a Python Module
- Importing a complete module
- Importing few function or constants from a module
3. Flow of Execution
4. User Input
Basics of Functions in Python
1. Functions & Their Parts
def sub1(a,b):
print(b,"-",a,"=",b-a)
- Function Name:
sub1
- Agruments Required:
a
&b
(2) - Number of Statements (in body) : one (1)
- Returned Value: none
- Objective: it takes 2 arguments and substracts first one from the second argument
def cube2(x):
x*x*x # a ')' at the end seems to ba a printing mistake
return x*x*x-x
- Function Name:
cube2
- Agruments Required:
x
(1) - Number of Statements (in body) : two
- Returned Value: result after subtracting a number from its cube
- Working: In first statement of the definition, the passed argument/number is multiplied thrice. In last statement, the same number is again multiplied thrice and then the it’s also subtracted from the resulting product i.e. cube. This final outcome is returned! Here first statement is not very significant.
def cube1(x):
return x*x*x
- Function Name:
cube1
- Agruments Required:
x
(1) - Number of Statements (in body) : one
- Returned Value: cube of a number
- Objective: finds the cube of a number i.e. passed as argument, by multiplying it thrice with itself
def greeting():
print("Welcome to Python")
- Function Name:
greeting
- Agruments Required: none
- Number of Statements (in body) : 1
- Returned Value: none
- Objective: prints a welcome messege
2. Function Call Statements for Above (4) Definitions
## variables, to use
x,y = 3,4
num = 5
for sub1()
sub1(x,y) # (h)
4 - 3 = 1
sub1(5,3) # (k)
3 - 5 = -2
for cube1()
cube1(x) # (i)
27
for cube2()
cube2(num) # (l)
120
for greeting()
greeting() # (g)
Welcome to Python
3. Few Functions
## To return the absolute value for given number
def absolute(num):
if num < 0:
num *= -1
return num
# using user defined function
print("|6| = ",absolute(6)) # 6
print("|-3| = ",absolute(-3)) # 3
|6| = 6
|-3| = 3
# using inbuilt function abs()
print("|6| = ",abs(6)) # 6
print("|-3| = ",abs(-3)) # 3
|6| = 6
|-3| = 3
## check for even / odd number
def chkOdd(num):
if num%2 == 0:
print(num, "is Even")
else:
print(num, "is Odd")
chkOdd(2)
chkOdd(3)
2 is Even
3 is Odd
Modules and More about the Functions
Modules in Python
Modules are just the python programs including various functions, classes and many other kinda definations.
Alone, they don’t play any majour role. But, the modules are necessary when we wish to use the functions or any other defination decleared in it. Inthis way, a python module provides a modularity.
A python module as also saved as a normal python program i.e. with the extention .py
and are imported using import
keyword.
the codes/modules present in current directory can be found here
Importing from same dir.
A Python Mdule to Pint a Wlcome Mssage
ASSUMING FOLLOWING BE THE MODULE hello.py
, PLACED IN THE CURRENT DIRECTORY
def greet():
print("Hey there!! Welcome to the Python Modules!")
# importing the module
import hello as greetings
# calling the function from module
greetings.greet()
Hey there!! Welcome to the Python Modules!
Importing from external/another dir.
import sys
sys.path.append('../dependancies/modules/')
import welcome
welcome.greeting()
Hey there!! Welcome to the Python Modules!
welcome.name = welcome.setName()
welcome.msg(welcome.name)
Hello World!!
welcome.name = welcome.setName("Ravi")
welcome.msg(welcome.name)
Hello Ravi!!
This module can be found here
Exercise
1. Module to find sum & product
import basicMath as m
print("2 + 3 = ",m.sum(2,3))
2 + 3 = 5
print("2 X 3 = ",m.product(2,3))
2 X 3 = 6
2. Python function to identify a leap year
def isLeap(year):
flag = False
if year%100 == 0 and year%400 == 0:
flag = True
elif year%100 != 0 and year%4 == 0:
flag = True
return flag
if(isLeap(2020)):
print("2020 is a leap year!")
else:
print("2020 is NOT a leap year!")
2020 is a leap year!
## True = Leap year | False = NOT Leap year
print(isLeap(1992))
print(isLeap(2000))
print(isLeap(1900))
print(isLeap(2100))
True
True
False
False
3. Local VS Global variables in python
# if there is only a Global variable with a name,
# it's value is used everywhere in the module/program
name = "Myname"
def caller():
print("Hey",name, "!!")
caller()
Hey Myname !!
# if there is only a Local variable with a name,
# it's value is used everywhere wuthin that particular function / class
def caller():
name = "Myname"
print("Hey",name, "!!")
caller()
Hey Myname !!
# if there are 2 or more variable with same name, (including Global and Local(s), both)
# keyword 'global' is used to call the global variable
name = "Myname"
def caller():
global name
name = "My name" # this would change the global variable's value
print(name," is not 'Myname'!!")
caller()
print(name)
My name is not 'Myname'!!
My name
4. Module to find pow(x,n)
import power
power.pow(2, 10)
1024
5. Create roll_D(noOfSides, noOfDice) and generate random roll values
# since default arguments can only come after defaults,
# making both the arguments default in order to maintain the order
import random as rand
def roll_D(noOfSides = 6, noOfDice = 1):
roll = 1
while roll <= noOfDice:
outcome = rand.randint(1,noOfSides)
print(outcome)
roll += 1
print("That's all")
Checking for given condition i.e. (6,3)
roll_D(6,3) # 3 dice with 6 faces, each
2
4
4
That's all
Some othe examples
roll_D() # one die with 6 faces
6
That's all
roll_D(8) # one die with 8 faces
1
That's all
roll_D(noOfDice = 2) # 2 dice with 6 faces, each
3
5
That's all
roll_D(7,3) # 3 dice with 7 faces, each
6
4
2
That's all
6. Prime / Non-Prime Function
def isPrime(num):
if num == 2 or num == 3:
flag = True
elif num%2 != 0:
for i in range(3, int(num/2)):
if num%i != 0:
flag = True
continue
else:
flag = False
break
else:
flag = False
return flag
num = 8
if(isPrime(num)):
print(num,"is Prime")
else:
print(num,"is NOT Prime")
8 is NOT Prime
num = 13
if(isPrime(num)):
print(num,"is Prime")
else:
print(num,"is NOT Prime")
13 is Prime
Sum of square of first and last 2 digits
def void(num):
if num not in range(1000,9999):
return -1
else:
first = int(num/100)
last = num%100
return first**2 + last**2
num = 235
res = void(num)
if res == -1:
print("Invalid input!!")
else:
print("Calculated result: ",res)
Invalid input!!
num = 2315
res = void(num)
if res == -1:
print("Invalid input!!")
else:
print("Calculated result: ",res)
Calculated result: 754
Check for Vowel
def isVowel(char):
vowels = ['a','e','i','o','u','A','E','I','O','U']
flag = False
if char in vowels:
flag = True
return flag
# prints True if passed charector is a Vowel
print(isVowel('u'))
print(isVowel('k'))
print(isVowel('m'))
print(isVowel('i'))
True
False
False
True
Mersenne Number
# declearing fun.
def mersenne(num):
return 2**num - 1
# input the value for number
n = input("Enter the number: ")
Enter the number: 5
# the result
print("Mersenne number is: ",mersenne(int(n)))
Mersene number is: 31