A function is a self-contained block of organized, reusable code that is used to perform some particular task. Functions provide better modularity for your application and a high degree of code reusing.
Suppose we want to perform a task several times, in such scenario, rather than writing code for that particular task repeatedly, we create a function for that task and call it when wewant to perform the task. Each function is given a name,using which we call it. A python may or may not return a value.
There are many built-in functions provided by python such as dir(), len(),abs() etc. User can also build their own functions, which are called as user-defined functions.
There are many advantages of using functions
a) They reduce duplication of code in a program.
b) They break large complex problem into small parts.
c) They help in improving the clarity of code(i.e. make the code easy to understand)
d) A piece of code can be resued as many times as we want with the help of functions.
Built-In Functions:
Built-in functions are the functions already defined in the python programming language; we can directly call them t perform a specific task. Every built-in function in python performs some particular task. For example, the math module has some mathematical built-in functionsthat perform task related to mathematics.
1. Type Conversion
In python programming, there are functions which are used to convert one type of data into another type of data. For example int,float and string
Int function can take any numer value and convert into integer value.
>>>int(10.5)
10 #Output
>>> int('python')
Traceback (most recent call last):
File "<pyshell#0>", line 1, in
int('python')
ValueError: invalid literal for int() with base 10: 'python'
>>> int('10')
10 #Output
In above example, we can see that, i first case the number 10.5 is converted to interger 10 but in second case, the 'python' is not a interger, that is why it gives a error, it means, string can not be converted but in third case, we have taken number '5' as a string and it is converted using int() function.
Now float() function converts integer value to floating-point value.
>>> float(10)
10.0 #Output
>>> float('20')
20.0 #Output
Finally python has a str() function which is used to convert the types into string.
>>> str(10)
'10' # output
2. Type Coercion
There is another kind of conversion in python language, known as implicit conversion. Implicit comversion is also known as type coercion and is automatically done bythe interpreter.
Type coercion is a process through which the python interpreter automatically converts a valu of one type into a valueof another type according to requirement.
>>>x=10.6
>>>x/2
5.3 #0utput
Here, in the above example, we make the denominatora float number. The python interpreter automatically converts the numerator into float and does the calculation.
3. Mathematical Functions
The math module is a standard module in Python and is always available. To use mathematical functions under this module, you have to import the module using import math.
>>>import math
This statement creates an object of module named math. Now,if we try to print this object, the interpreter will give some information about it.
>>>print math
<module 'math' (built-in)>
for example, calculate the square root of a given number
import math;
math.sqrt(4)
#output
4
Frequently used In-built mathematical functions are as follows
Sr. No. | Function | Description |
1 | ceil(x) | Returns the smallest integer greater than or equal to x. |
2 | floor(x) | Returns the largest integer less than or equal to x |
3 | fabs(x) | Returns the absolute value of x |
4 | factorial(x) | Returns the factorial of x |
5 | fmod(x,y) | Returns the remainder when x is divided by y |
6 | pow(x,y) | Returns x raised to the power y |
7 | sqrt(x) | Returns the square root of x |
8 | sin(x) | Returns the sine of x |
9 | cos(x) | Returns the cosine of x |
10 | tan(x) | Returns the tangent of x |
11 | pi | Mathematical constant, the ratio of circumference of a circle to it's diameter (3.14159...) |
Example:
Write python script for the mathematical functions like sqrt( ), foor( ), ceil( ), fabs( ), factorial( )
import math;
ch='y'
while(ch=='y' or ch=='Y'):
print("1. Square Root")
print("2. Floor of number")
print("3. Ceil of Number")
print("4. Absolute of Number")
print("5. Factorial of Number")
choice=int(input("Enter Your choice : "))
if(choice==1):
x=4
print("Suqare Root of 4 is : ",math.sqrt(x))
elif(choice==2):
x=10.2
print("The ceil value of 10.2 is : ",math.ceil(x))
#print(math.ceil(x))
elif(choice==3):
x=10.8
print("The floor value of 10.2 is : ",math.floor(x))
elif(choice==4):
x=-10
print("Absolute value of -10 is : ",math.fabs(x))
elif(choice==5):
x=5
print("Factorial of 5 is : ",math.acosfactorial(x))
else:
print("Wrong Choice")
ch=input("Want to continue(Y/N) : ")
print("Successful!!")
3.1 Date and Time
Python has defined a module, “time” which allows us to handle various operations regarding time, its conversions and representations, which find its use in various applications in life. The beginning of time is started measuring from 1 January, 12:00 am, 1970 and this very time is termed as “epoch” in Python.
Opeartions on Time:
Python provides the built-in modules time and claendar through whuich we can handle date and time in several ways. For example, we can use these modules to get the current time and date. In order to use the time module, we need to import it into our program first. Simillarly, for working with dates, we have to import the calendar module first.
#!/usr/bin/python3
import time; # This is required to include time module.
ticks = time.time()
print ("Number of ticks since 12:00am, January 1, 1970:", ticks)
#Output
Number of ticks since 12:00am, January 1, 1970: 1566946228.845661
However, dates before the epoch cannot be represented in this form. Dates in the far future also cannot be represented this way - the cutoff point is sometime in 2038 for UNIX and Windows.
What is Time Tuple?
Many of the Python's time functions handle time as a tuple of 9 numbers, as shown below −
Index | Field | Values |
---|---|---|
0 | 4-digit year | 2016 |
1 | Month | 1 to 12 |
2 | Day | 1 to 31 |
3 | Hour | 0 to 23 |
4 | Minute | 0 to 59 |
5 | Second | 0 to 61 (60 or 61 are leap-seconds) |
6 | Day of Week | 0 to 6 (0 is Monday) |
7 | Day of year | 1 to 366 (Julian day) |
8 | Daylight savings | -1, 0, 1, -1 means library determines DST |
for example-
import time
print (time.localtime())
#output
time.struct_time(tm_year=2019, tm_mon=8, tm_mday=27, tm_hour=13, tm_min=3, tm_sec=4, tm_wday=1, tm_yday=239, tm_isdst=0)
Getting Current date and Time:
To translate a time instant from seconds since the epoch floating-point value into a timetuple, pass the floating-point value to a function (e.g., localtime) that returns a time-tuple with all valid nine items.
import time
localtime = time.localtime(time.time())
print ("Local current time :", localtime)
#Output
Local current time : time.struct_time(tm_year=2019, tm_mon=8, tm_mday=27, tm_hour=13, tm_min=6, tm_sec=10, tm_wday=1, tm_yday=239, tm_isdst=0)
Getting Formatted Date and Time:
Though we can format time and date according to our interest, the most common method used to get time in readable format is asctime()
import time;
localtime=time.asctime(time.localtime(time.time()))
print("Local Current Time : ",localtime)
# Output
Local Current Time : Thu Aug 22 09:12:17 2019
Here we make use of the asctime() function to get a readable format of date and time.
Getting Calendar for a Month:
Python provides us a calendar module through which we can use yearly and monthly calander according to our requirement. In the example below, we print the calendar for a month of August, 2019.
import calendar;
c=calendar.month(2019,8)
print("Calendar for August, 2019 : \n",c)
#Output
Calendar for August, 2019 :
August 2019
Mo Tu We Th Fr Sa Su
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Some Time Related Functions:
1. time.time()
The time( ) function returns the number of seconds passed since epoch.
For Unix system, January 1, 1970, 00:00:00
at UTC is epoch (the point where time begins).
import time
seconds = time.time()
print("Seconds since epoch =", seconds)
2. time.ctime()
The time.ctime() function takes seconds passed since epoch as an argument and returns a string representing local time.
import time
# seconds passed since epoch
seconds = 1545925769.9618232
local_time = time.ctime(seconds)
print("Local time:", local_time)
#Output
Local time: Thu Dec 27 15:49:29 2018
Before we talk about other time-related functions, let's explore time.struct_time
class in brief.
Several functions in the time
module such as gmtime()
, asctime()
etc. either take time.struct_time
object as an argument or return it.
Here's an example of time.struct_time
object.
time.struct_time(tm_year=2018, tm_mon=12, tm_mday=27,
tm_hour=6, tm_min=35, tm_sec=17,
tm_wday=3, tm_yday=361, tm_isdst=0)
3. time.localtime()
The localtime()
function takes the number of seconds passed since epoch as an argument and returns struct_time
in local time.
import time
result = time.localtime(1545925769)
print("result:", result)
print("\nyear:", result.tm_year)
print("tm_hour:", result.tm_hour)
#Output
result: time.struct_time(tm_year=2018, tm_mon=12, tm_mday=27, tm_hour=15, tm_min=49, tm_sec=29, tm_wday=3, tm_yday=361, tm_isdst=0)
year: 2018
tm_hour: 15
4. time.asctime()
import time
t = (2018, 12, 28, 8, 44, 4, 4, 362, 0)
result = time.asctime(t)
print("Result:", result)
#Output
Result: Fri Dec 28 08:44:04 2018
There are many other functions to study time in details
3.2 dir( ) Function
dir( ) takes an object as an argument . It returns a list of strings which are names of members of that object. If object is module, it will list sub-modules, functions provided by variables,constants etc. Its good tool to learn and understand about module or objects.
import time
x=dir(time)
print(x)
# Output
['_STRUCT_TM_ITEMS', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'altzone', 'asctime', 'clock', 'ctime', 'daylight', 'get_clock_info', 'gmtime', 'localtime', 'mktime', 'monotonic', 'perf_counter', 'process_time', 'sleep', 'strftime', 'strptime', 'struct_time', 'time', 'timezone', 'tzname']
include math
x=dir(math)
print(x)
#Output
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
3.2 help( ) Function
help( ) function is built-in function in python programming language which is used to invoke the help system. It takes an object as an argument. It gives all the detailed information about that object like if it's a module, then it will tell you about the submodules,functions, variables and constants in details.
import math;
help(math.sin)
#Output
Help on built-in function sin in module math:
sin(...)
sin(x)
Return the sine of x (measured in radians).
Example:
Write a python script to print current date and time,calendar of given month of the year and and also test dir() and help() function for any given module.
import time;
import calendar;
import math
ch='y'
while(ch=='y' or ch=='Y'):
print("1. Date and Time")
print("2. Calendar")
print("3. Directory")
print("4. Help")
choice=int(input("Enter your choice : "))
if choice == 1:
print("Date and Time in Specific Format")
localtime=time.asctime(time.localtime(time.time()))
print("Local Current Time : ",localtime)
elif choice == 2:
# Getting Calendar for a Month
month=int(input("Enter month : "))
year=int(input("Enter year : "))
c=calendar.month(year,month)
print(c)
elif choice==3:
a=dir(time)
print(a)
elif choice==4:
help(math.sin)
else:
print("Wrong Choice")
ch=input("Want to continue(Y/N) : ")
print("Successful !!")
ord() Function:
It coverts the given string of length one, return an integer representing the unicode code point of the character. For example, ord(‘a’) returns the integer 97.
# Python program to print
# ASCII Value of Character
ch=input("Enter any character : ")
print("The ASCII value of", ch, "is ", ord(ch))
#Output
Enter any character : A
The ASCII value of A is 65
Reference:
1. E Balagurusamy, "Introduction to computing and Problem Solving using python", McGraw Hill Education(India) Pvt. Ltd., 1e, 2016,ISBN Edition-13: 978-93-5260-2802 and ISBN-10: 93-5260-258-7