Python Built-in Functions
Python Built-in functions are standard library functions that are part of language itself. There are lots of built-in functions in Python programming.
Built-in functions help in the optimisation, as they have clean and clear syntax and easy to use. For example, with the help of sum()
function we can easily find the sum of the elements of the list.
Let’s learn about the most used built-in functions with the help of Examples.
Complex() function
A complex number is the combination of the real and an imaginary number. We can easily create a complex number with the help of complex()
function. By using complex()
Function, we can convert a string or number to the complex number. This function returns a complex number like this 3+5j.
Example of complex() function
print(complex(2)) # integer
print(complex(2, 3))
print(complex(2.3)) # float
print(complex(2, 3.2))
print(complex('1+2j')) # string
(2+0j)
(2+3j)
(2.3+0j)
(2+3.2j)
(1+2j)
Note: While changing a string to complex, we must take care of the white space. A string must not contain white space. Otherwise, Python will throw an error. For example, ‘3+4j’ is valid and ‘3 + 3j’ will throw an error.
dict() Function
By the help of dict()
function, we can create a new dictionary.
Example of creating dictionary using the dict() function
my_dictionary = dict(
Name="Deepak",
Class=9,
Subject="IT"
)
print(my_dictionary)
{‘Name’: ‘Deepak’, ‘Class’: 9, ‘Subject’: ‘IT’}
bin() Function
With the help of the Python bin()
function, we can get the binary value of integer type number. In other words, it returns the binary version of a number.
Example to convert numbers in binary conversion
number = 15
print(bin(number))
print(bin(456))
0b1111
0b111001000
Description of Output
Here, 1111 is the binary value of 15 and 111001000 is the binary value of the 456
divmod() Function
With the help of the Python divmod()
function, we can get both the quotient and remainder. It return the quotient and remainder when the parameter 1 is divided by parameter 2.
Example of divmod() function
print(divmod(6,2))
(3, 0)
Description of Output
When 6 is divied by 3 , the quotient and remainder are 3 and 0 respectively.
float() function
With the help of float()
function, we can convert any datatype to the float.
Example of float function
var_1 = 321 # this is integer
var_2 = 321.321 # this is float
var_3 = "321" # this is string
print(float(var_1))
print(float(var_2))
print(float(var_3))
321.0
321.321
321.0
format() function
With the help of format() function, we specify the specific format of the number. For example, we want to specify that a number is positive or negative.
Example of format() function
num_1 = 232
print(format(num_1, '+')) # return + if number is positive
num_2 = -41
print(format(num_2, '+')) # return - if number is negative
+232
-41
Exercises & Assignments |
---|
No Content Found. |
Interview Questions & Answers |
---|
No Content Found. |