Library Functions

Chapter 6 • Python
Chapter 6 • Python

Library Functions

Explore Python's powerful built-in modules. From Math and Random objects to deep String manipulation and detailed Date-Time tracking!

Math Module
Random Numbers
String Mgmt
Date/Time

Introduction :

Python में कुछ pre-define module पहले से ही होते हैं। जिन्हें library module कहा जाता है। प्रत्येक module में कुछ built-in functions शामिल होते हैं, जिन्हें library function कहा जाता है।

प्रत्येक function किसी विशेष कार्य को करने के लिए होता है।

  • Ex: (Math, Random and string) → Module
  • Ex: abs(), sqrt(), pow(), str(), islower() → Function

किसी भी module के function का उपयोग करने के लिए सर्वप्रथम module को program में import किया जाता है। Module 3 प्रकार से import किया जा सकता है:

1. To import entire module:

Import statement के द्वारा module को import किया जा सकता है।

python
import <module name>, <m2>…

import math, string
print(math.sqrt(25))

# Output:
# 5

2. Import selected object of module:

From import statement के द्वारा selected function import किया जा सकता है।

python
from <module name> import <function name>

from math import pi, sqrt, pow
print(pi) # 3.14
print(sqrt(25)) # 5
print(pow(3,2)) # 9
print(math.sqrt(36)) # Error (because complete math is not imported)

3. Import all object of module:

From import statement के द्वारा module के सभी object import किए जा सकते हैं।

python
from <module name> import *

from math import *

Math Module :

Math module में विभिन्न प्रकार के Mathematical functions मौजूद हैं।

(1) abs()निरपेक्ष मान (absolute value) return करता है
python
print(abs(-32.8))
# Output: 32.8
(2) sqrt()वर्गमूल निकालने के लिए
python
import math
print(math.sqrt(121))
# Output: 11.0
(3) exp()e^x की value return करता है

e = 2.718281

python
print(math.exp(3))
# Output: 20.085536
(4) ceil()highest integer में round off करता है
python
print(math.ceil(3.2)) # 4
print(math.ceil(3)) # 3
print(math.ceil(-20.4)) # -20
(5) floor()lowest integer में round off करता है
python
print(math.floor(3.2)) # 3
print(math.floor(3)) # 3
print(math.floor(-20.4)) # -21
(6) log()natural logarithm calculate करता है
python
print(math.log(2.34))
# Output: 0.850150929
(7) log10()base 10 logarithm देता है
python
print(math.log10(2.34))
# Output: 0.369215857
(8) pow()x^y की value return करता है
python
print(math.pow(8,2))
# Output: 64.0
(9) sin() / (10) cos() / (11) tan()Trigo values return करता है (radian में input)
python
print(math.sin(30 * 3.14 / 180))
print(math.cos(60 * 3.14 / 180))
(12) degrees() / (13) radians()radian को degree में, या degree को radian में convert
python
print(math.degrees(1.0472))
# 60.00014
(14) trunc()floating number का decimal part हटा देता है
python
print(math.trunc(6.97))
# Output: 6

Advanced Mathematical Programs :

python
import math
x = float(input("enter value of x"))
cal = math.exp(x) + math.cos(math.radians(x)) + math.sqrt(x)
print("Output is", cal)

python
from math import log, sqrt
x = int(input("enter value of x"))
y = int(input("enter value of y"))
cal = log(sqrt(x/y))
print(cal)

Random Module :

Random number generate करने के लिए इस module का उपयोग होता है।

(1) random()0 से 1 के बीच number देता है
python
import random
print(random.random())
(2) randint()दो integer के बीच random number देता है
python
import random
print(random.randint(20,25))
# Example Output: 24

String Manipulations :

String single, double या triple quotes में लिखा जा सकता है। हर character का index होता है।

Forward index  →  0  1  2  3  4  5
                 P  Y  T  H  O  N
Backward index → -6 -5 -4 -3 -2 -1

Accessing example:

python
# To get 'Y'
nm = "PYTHON"
print(nm[1])

Program - Iterate forward & backward index :

python
S = "PYTHON"
for a in range(0,6):
    print(S[a], "   ", S[-1-a])

Common String Functions :

(1) len()
string की length बताता है
print(len("Python")) # 6
(2) ord()
ASCII value देता है
print(ord('A')) # 65
(3) chr()
ASCII से character देता है
print(chr(65)) # A
(4) str()
number को string में convert करता है
print(str(123)) # '123'

String Methods :

(1) capitalize()पहला letter capital करता है
python
print('asdf'.capitalize()) # Asdf
(2) find()substring की first occurrence देता है
python
print('python'.find('p')) # 0
(3) isalnum()alphanumeric check करता है
python
print('@#@'.isalnum()) # False
(4) isalpha()alphabet check करता है
python
print('python'.isalpha()) # True
(5) isdigit()digit check करता है
python
print('python'.isdigit()) # False
(6) islower()small letters check करता है
python
print('upper'.islower()) # True
(7) isupper()capital letters check करता है
python
print('UPPER'.isupper()) # True
(8) isspace()space check करता है
python
print(' '.isspace()) # True
(9) lower()capital → small
python
print('UPPER'.lower()) # upper
(10) upper()small → capital
python
print('upper'.upper()) # UPPER
(11) lstrip()left side spaces हटाता है
python
print('  India'.lstrip()) # India
(12) rstrip()right side spaces हटाता है
python
print('India  '.rstrip()) # India
(13) strip()दोनों side spaces/characters हटाता है
python
print('***Python***'.strip('*')) # Python
(14) split()string को parts में divide करता है
python
print('Honesty is the best'.split(' '))
# ['Honesty', 'is', 'the', 'best']
(15) join()elements को जोड़ता है
python
print(' '.join('python'))
# p y t h o n
(16) encode()string को code में convert करता है
python
s = 'hello'.encode('utf-8')
(17) decode()encoded string को वापस convert करता है
python
print(s.decode('utf-8'))
(18) endswith()suffix check करता है
python
print('Rakesh kumar'.endswith('kumar')) # True
(19) startswith()prefix check करता है
python
print('Rakesh kumar'.startswith('R')) # True
(20) partition()string को 3 parts में divide करता है
python
print('Python is a OOPS based language'.partition('OOPS'))

Date & Time Function :

Python में time और date को handle करने के लिए 2 modules होते हैं:

  • time module
  • calendar module

यह modules समय को 8 values के tuple में store करते हैं।

IndexFieldValues
0Year4-digit (जैसे 2008)
1Month1 to 12
2Day1 to 31
3Hour0 to 23
4Minute0 to 59
5Second0 to 60 (61 leap second)
6Day of week0 to 6 (0 = Monday)
7Day of year1 to 366

TIME MODULE

(1) time()यह function 1 January 1970 (12:00 AM) से अब तक के seconds return करता है।
python
import time
t = time.time()
print(t)
(2) localtime()seconds को time tuple में convert करता है।
python
import time
t = time.localtime(time.time())

print("Current time is:", t)
print("Current month is:", t[1])
(3) ctime()current date & time readable format में दिखाता है।
python
import time
print(time.ctime())

# Output:
# Fri Dec 17 10:30:00 2021
(4) mktime()time tuple को seconds में convert करता है।
python
import time
print(time.mktime(time.localtime()))
(5) sleep()program को कुछ seconds के लिए रोक देता है।
python
import time
time.sleep(5)
(6) strftime()यह function time tuple को format करके string में convert करता है।
Syntax
python
time.strftime(<format>, <time tuple>)
CodeMeaning
%aWeekday short name
%AFull weekday name
%bShort month name
%BFull month name
%mMonth (1–12)
%dDay (1–31)
%DDate format (%m/%d/%y)
%HHour (0–23)
%IHour (1–12)
%MMinute
%SSecond
%pAM/PM
%yYear (2 digit)
%YYear (4 digit)
%jDay of year (001–366)
%UWeekday no (1–7)
%nNew line
%tTab
Example
python
import time
t = (2009,2,17,11,3,38,1,48,0)

print(time.strftime("%b %d %Y %I:%M:%S", t))

# Output:
# Feb 17 2009 11:03:38
(7) strptime()यह function string को time tuple में convert करता है।
Syntax
python
time.strptime(<time>, <format>)
Example
python
import time
print(time.strptime("30 Aug 1961", "%d %b %Y"))

CALENDAR MODULE

(1) calendar()यह पूरे year का calendar return करता है (multi-line string में)
Syntax
python
calendar.calendar(<year>, <w>, <l>, <c>)
  • w → width
  • l → lines
  • c → space between months
Example
python
import calendar
print(calendar.calendar(2021, w=3, l=1, c=6))
(2) isleap()check करता है कि year leap year है या नहीं
python
import calendar
print(calendar.isleap(2020))  # True
(3) leapdays()दो years के बीच leap years की संख्या देता है
python
import calendar
print(calendar.leapdays(2000, 2020))  # 5
(4) month()किसी specific month का calendar देता है
python
import calendar
print(calendar.month(2021, 12, w=2, l=1))
(5) monthcalendar()month का calendar nested list में देता है
python
import calendar
print(calendar.monthcalendar(2022, 1))
(6) monthrange()month का पहला weekday और total days देता है
python
import calendar
print(calendar.monthrange(2019, 8))

# Output:
# (3, 31)
(7) setfirstweekday()week का first day set करता है
python
import calendar
calendar.setfirstweekday(5)
print(calendar.prmonth(2019, 6))

# Weekday code:
# 0 = Monday
# 6 = Sunday
(8) weekday()given date का weekday code return करता है
python
import calendar
print(calendar.weekday(2019, 4, 12))

Practice Questions :

Math Module से सम्बंधित महत्वपूर्ण प्रश्न (इन्हें Python में solve करने का प्रयास करें):

Q1
√(25 + 36) + log₁₀(100) + e²
Q2
ceil(3.4) + floor(7.8) + √(49)
Q3
√(16 + 9) + sin(30°) + cos(60°)
Q4
e³ + log(10) + √(81)
Q5
floor(9.7) + ceil(2.1) + tan(45°)
Q6
√( (5² + 12²) ) + log₁₀(1000)
Q7
e² + sin(90°) + cos(0°) + √(64)
Q8
ceil(5.2) + floor(3.9) + log(2.5)
Q9
√(100 + 25) + e³ + tan(45°)
Q10
log₁₀(100) + √(49) + ceil(6.1) + floor(8.9)
Hi! 👋
KnoblyAI
Online

Hello! 👋

Your futuristic AI learning companion

KnoblyAI can make mistakes. Double-check important replies.