Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
34 views

Built-In Functions in Python

The document discusses 19 built-in functions in Python including abs(), bin(), bool(), chr(), complex(), dict(), divmod(), eval(), float(), format(), help(), input(), len(), list(), max(), min(), ord(), range(), and str(). Each function is explained with examples showing how it works.

Uploaded by

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

Built-In Functions in Python

The document discusses 19 built-in functions in Python including abs(), bin(), bool(), chr(), complex(), dict(), divmod(), eval(), float(), format(), help(), input(), len(), list(), max(), min(), ord(), range(), and str(). Each function is explained with examples showing how it works.

Uploaded by

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

BUILT IN FUNCTIONS IN PYTHON

Built in Functions
1. abs()

The abs() is one of the most popular Python built-in functions, which returns the
absolute value of a number.

A negative value’s absolute is that value is positive.

>>> abs(-7)
Output

7
2. bin()
The bin() method converts and returns the binary equivalent string of a given
integer.

Example 1: Convert integer to binary using bin()


number = 5
print('The binary equivalent of 5 is:', bin(number))

Output

The binary equivalent of 5 is: 0b101


3. bool()
The bool() method converts a value to Boolean (True or False) using the standard
truth testing procedure.

bool() parameters
It's not mandatory to pass a value to bool(). If you do not pass a value, bool() returns
False.

In general use, bool() takes a single parameter value.

Return Value from bool()


bool() returns:
• False if the value is omitted or false
• True if the value is true
The following values are considered false in Python:

• None
• False
• Zero of any numeric type. For example, 0, 0.0, 0j
• Empty sequence. For example, (), [], ''.
• Empty mapping. For example, {}

All other values except these values are considered true.


Example:

test = []
print(test,'is',bool(test))
test = [0]
print(test,'is',bool(test))
test = 0.0 Output
print(test,'is',bool(test))
test = None [] is False
print(test,'is',bool(test)) [0] is True
test = True 0.0 is False
print(test,'is',bool(test)) None is False
test = 'Easy string' True is True
print(test,'is',bool(test)) Easy string is True
4. chr()
The chr() method returns a character (a string) from an integer (represents
unicode code point of the character).

Example :

print(chr(97))
print(chr(65))

Output

a
A
5. ord()
The ord() function returns an integer representing the Unicode character.

Example:

print(ord('5')) # 53
print(ord('A')) # 65
print(ord('$')) # 36

Output

53
65
36
6. complex()
The complex() method returns a complex number when real and imaginary parts are
provided, or it converts a string to a complex number.

Example :
z = complex(2, -3)
print(z)
z = complex(1)
print(z)
z = complex() Output
print(z)
z = complex('5-9j') (2-3j)
print(z) (1+0j)
0j
(5-9j)
7. dict()
The dict() constructor creates a dictionary in Python.

Example :
numbers = dict(x=5, y=0)
print('numbers =', numbers)
print(type(numbers))

empty = dict() Output


print('empty =', empty)
print(type(empty)) numbers = {'y': 0, 'x': 5}
<class 'dict'>
empty = {}
<class 'dict'>
8. divmod()
The divmod() method takes two numbers and returns a pair of numbers (a tuple)
consisting of their quotient and remainder.

Example: Output
print('divmod(8, 3) = ', divmod(8, 3))
print('divmod(3, 8) = ', divmod(3, 8)) divmod(8, 3) = (2, 2)
print('divmod(5, 5) = ', divmod(5, 5)) divmod(3, 8) = (0, 3)
divmod(5, 5) = (1, 0)
# divmod() with Floats divmod(8.0, 3) = (2.0, 2.0)
print('divmod(8.0, 3) = ', divmod(8.0, 3)) divmod(3, 8.0) = (0.0, 3.0)
print('divmod(3, 8.0) = ', divmod(3, 8.0)) divmod(7.5, 2.5) = (3.0, 0.0)
print('divmod(7.5, 2.5) = ', divmod(7.5, 2.5))
9. eval()
The eval() method parses the expression passed to this method and runs python
expression (code) within the program.

Example :
x=1
print(eval('x + 1'))

Output

2
10. exec()
The exec() method executes the dynamically created program, which is either a string
or a code object.

Example :
program = 'a = 5\nb=10\nprint("Sum =", a+b)'
exec(program)

Output

Sum = 15
11. float()
The float() method returns a floating point number from a number or a string.

Example :
# for integers
print(float(10))
# for floats Output
print(float(11.22))
# for string floats 10.0
print(float("-13.33")) 11.22
# for string floats with whitespaces -13.33
print(float(" -24.45")) -24.45
# string float error ValueError: could not convert string to float:
print(float("abc")) 'abc'
12. format()
The built-in format() method returns a formatted representation of the given value
controlled by the format specifier.

Example: Number formatting with format()


# d, f and b are type
# integer
print(format(123, "d"))
# float arguments Output
print(format(123.4567898, "f"))
# binary format 123
print(format(12, "b")) 123.456790
1100
13. help()
The help() method calls the built-in Python help system.
If string is passed as an argument, name of a module, function, class, method,
keyword, or documentation topic, and a help page is printed.

Example:
>>> help(list)
>>> help(dict)
>>> help(print)
14. hex()
The hex() function converts an integer number to the corresponding hexadecimal
string.
Example :
number = 435
print(number, 'in hex =', hex(number))

number = 0
print(number, 'in hex =', hex(number)) Output

number = -34 435 in hex = 0x1b3


print(number, 'in hex =', hex(number)) 0 in hex = 0x0
-34 in hex = -0x22
returnType = type(hex(number)) Return type from hex() is <class 'str'>
print('Return type from hex() is', returnType)
15. input()
The input() method reads a line from input, converts into a string and returns it.

Example 1: How input() works in Python?


# get input from user

inputString = input()
print('The inputted string is:', inputString)

Output

Python is interesting.
The inputted string is: Python is interesting
Example 2: Get input from user with a prompt
# get input from user

inputString = input('Enter a string:')

print('The inputted string is:', inputString)

Output

Enter a string: Python is interesting.


The inputted string is: Python is interesting
16. len()
The len() function returns the number of items (length) in an object.

Example 1: How len() works with tuples, lists and range?


testList = []
print(testList, 'length is', len(testList))
testList = [1, 2, 3]
print(testList, 'length is', len(testList)) Output
testTuple = (1, 2, 3)
print(testTuple, 'length is', len(testTuple)) [] length is 0
testRange = range(1, 10) [1, 2, 3] length is 3
print('Length of', testRange, 'is', len(testRange)) (1, 2, 3) length is 3
Length of range(1, 10) is 9
Example 2: How len() works with strings

testString = ''
print('Length of', testString, 'is', len(testString))

testString = 'Python'
print('Length of', testString, 'is', len(testString))

Output

Length of is 0
Length of Python is 6
Example 3: How len() works with dictionaries and sets
testSet = {1, 2, 3}
print(testSet, 'length is', len(testSet))
# Empty Set
testSet = set()
print(testSet, 'length is', len(testSet))
testDict = {1: 'one', 2: 'two'}
print(testDict, 'length is', len(testDict))
testDict = {}
print(testDict, 'length is', len(testDict))

Output
{1, 2, 3} length is 3
set() length is 0
{1: 'one', 2: 'two'} length is 2
{} length is 0
17. list()
The list() constructor returns a list in Python.

Example 1: Create lists from string, tuple, and list


# empty list
print(list())
# vowel string
vowel_string = 'aeiou'
print(list(vowel_string)) Output
# vowel tuple
vowel_tuple = ('a', 'e', 'i', 'o', 'u') []
print(list(vowel_tuple)) ['a', 'e', 'i', 'o', 'u']
# vowel list ['a', 'e', 'i', 'o', 'u']
vowel_list = ['a', 'e', 'i', 'o', 'u'] ['a', 'e', 'i', 'o', 'u']
print(list(vowel_list))
Example 2: Create lists from set and dictionary
# vowel set
vowel_set = {'a', 'e', 'i', 'o', 'u'}
print(list(vowel_set))

# vowel dictionary
vowel_dictionary = {'a': 1, 'e': 2, 'i': 3, 'o':4, 'u':5}
print(list(vowel_dictionary))
Output

['a', 'o', 'u', 'e', 'i']


['o', 'e', 'a', 'u', 'i']

Note: In the case of dictionaries, the keys of the dictionary will be the items of the list. Also, the order
of the elements will be random.
18. max()
The Python max() function returns the largest item in an iterable. It can also be used to
find the largest item between two or more parameters.

Example 1: Get the largest item in a list


number = [3, 2, 8, 5, 10, 6]
largest_number = max(number);

print("The largest number is:", largest_number)

Output

The largest number is: 10


If the items in an iterable are strings, the largest item (ordered alphabetically) is
returned.

Example 2: the largest string in a list


languages = ["Python", "C Programming", "Java", "JavaScript"]
largest_string = max(languages);

print("The largest string is:", largest_string)

Output

The largest string is: Python


Example 4: Find the maximum among the given numbers
result = max(4, -5, 23, 5)
print("The maximum number is:", result)

Output

The maximum number is: 23


19. min()
The Python min() function returns the smallest item in an iterable. It can also be used
to find the smallest item between two or more parameters.

Example 1: Get the smallest item in a list


number = [3, 2, 8, 5, 10, 6]
smallest_number = min(number);

print("The smallest number is:", smallest_number)


Output

The smallest number is: 2


If the items in an iterable are strings, the smallest item (ordered alphabetically) is
returned.

Example 2: The smallest string in a list


languages = ["Python", "C Programming", "Java", "JavaScript"]
smallest_string = min(languages);

print("The smallest string is:", smallest_string)

Output

The smallest string is: C Programming


20. oct()
The oct() function takes an integer number and returns its octal representation.

Example :
# decimal to octal
print('oct(10) is:', oct(10))
# binary to octal
print('oct(0b101) is:', oct(0b101))
# hexadecimal to octal
print('oct(0XA) is:', oct(0XA))

Output
oct(10) is: 0o12
oct(0b101) is: 0o5
oct(0XA) is: 0o12
21. pow()
The pow() function returns the power of a number.

Example :
# positive x, positive y (x**y)
print(pow(2, 2)) # 4
# negative x, positive y Output
print(pow(-2, 2)) # 4 4
# positive x, negative y 4
print(pow(2, -2)) # 0.25 0.25
# negative x, negative y 0.25
print(pow(-2, -2)) # 0.25
Example 2: pow() with three arguments (x**y) % z
x=7
y=2
z=5

print(pow(x, y, z)) # 4
Output

4
Here, 7 powered by 2 equals 49. Then, 49 modulus 5 equals 4.
22. print()
The print() function prints the given object to the standard output device (screen) or
to the text stream file.
Example 1: print("Python is fun.")
a=5
# Two objects are passed
print("a =", a)
b=a
# Three objects are passed
print('a =', a, '= b')

Output
Python is fun.
a=5
a=5=b
Example 2: print() with separator and end parameters
a=5
print("a =", a, sep='00000', end='\n\n\n')
print("a =", a, sep='0', end='')

Output

a =000005

a =05
23. range()
The range() type returns an immutable sequence of numbers between the given
start integer to the stop integer.

range() Parameters
range() takes mainly three arguments having the same use in both definitions:

• start - integer starting from which the sequence of integers is to be returned


• stop - integer before which the sequence of integers is to be returned.
• The range of integers ends at stop - 1.
• step (Optional) - integer value which determines the increment between each
integer in the sequence
Example 1:
# empty range
print(list(range(0)))

# using range(stop)
print(list(range(10)))

# using range(start, stop)


print(list(range(1, 10)))

Output

[]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Example 2: Create a list of even number between the given numbers using
range()
start = 2
stop = 14
step = 2

print(list(range(start, stop, step)))

Output

[2, 4, 6, 8, 10, 12]


Example 3: How range() works with negative step?
start = 2
stop = -14
step = -2

print(list(range(start, stop, step)))

# value constraint not met


print(list(range(start, 14, step)))

Output

[2, 0, -2, -4, -6, -8, -10, -12]


[]
24. reversed()
The reversed() function returns the reversed iterator of the given sequence.

Example 1: Using reveresed() in string, tuple, list, and range


# for string
seq_string = 'Python'
print(list(reversed(seq_string)))
# for tuple
seq_tuple = ('P', 'y', 't', 'h', 'o', 'n')
print(list(reversed(seq_tuple))) Output
# for range
seq_range = range(5, 9) ['n', 'o', 'h', 't', 'y', 'P']
print(list(reversed(seq_range))) ['n', 'o', 'h', 't', 'y', 'P']
# for list [8, 7, 6, 5]
seq_list = [1, 2, 4, 3, 5] [5, 3, 4, 2, 1]
print(list(reversed(seq_list)))
25. round()
The round() function returns a floating-point number rounded to the specified
number of decimals.
Example 1:
# for integers
print(round(10))

# for floating point


print(round(10.7))
Output
# even choice
print(round(5.5)) 10
11
6
26. set()
The set() builtin creates a set in Python.
Example 1: Create sets from string, tuple, list, and range
# empty set
print(set())
# from string
print(set('Python'))
# from tuple Output
print(set(('a', 'e', 'i', 'o', 'u')))
# from list set()
print(set(['a', 'e', 'i', 'o', 'u'])) {'P', 'o', 't', 'n', 'y', 'h'}
# from range {'a', 'o', 'e', 'u', 'i'}
print(set(range(5))) {'a', 'o', 'e', 'u', 'i'}
{0, 1, 2, 3, 4}
27. sorted()
The sorted() function returns a sorted list from the items in an iterable.

Example 1: Sort string

# vowels list
py_list = ['e', 'a', 'u', 'o', 'i']
print(sorted(py_list))

Output

['a', 'e', 'i', 'o', 'u']


Example 2: Sort in descending order

# set
py_set = {'e', 'a', 'u', 'o', 'i'}
print(sorted(py_set, reverse=True))

Output

['u', 'o', 'i', 'e', 'a']


28. sum()
The sum() function adds the items of an iterable and returns the sum.

Example: Working of Python sum()


numbers = [2.5, 3, 4, -5]

# start parameter is not provided


numbers_sum = sum(numbers)
print(numbers_sum)

Output

4.5
29. type()
The type() function either returns the type of the object or returns a new type object
based on the arguments passed.

Example 1: Get Type of an Object


numbers_list = [1, 2]
print(type(numbers_list))

numbers_dict = {1: 'one', 2: 'two'}


print(type(numbers_dict))
Output

<class 'list'>
<class 'dict'>
Example 2:
a = ('apple', 'banana', 'cherry')
b = "Hello World"
c = 33

x = type(a)
y = type(b)
z = type(c) Output:
<class 'tuple'>
print(x) <class 'str'>
print(y) <class 'int'>
print(z)
30. tuple()
The tuple() builtin can be used to create tuples in Python.
A tuple is an immutable sequence type. One of the ways of creating tuple is by
using the tuple() construct.
Example: Create tuples using tuple()
t1 = tuple()
print('t1 =', t1)

# creating a tuple from a list


t2 = tuple([1, 4, 6])
print('t2 =', t2)

# creating a tuple from a string Output


t1 = tuple('Python')
print('t1 =',t1) t1 = ()
t2 = (1, 4, 6)
# creating a tuple from a dictionary t1 = ('P', 'y', 't', 'h', 'o', 'n')
t1 = tuple({1: 'one', 2: 'two'}) t1 = (1, 2)
print('t1 =',t1)
THANK YOU

You might also like