Python Built-In Functions
Table Of Contents:
- What Is A Built-In Function?
- Different Built-In Functions.
(1) What Is A Built-In Function?
- A built-in function is a function that is already available in a programming language, application, or another tool that can be accessed by end users.
- The end user can directly call the function to use it.
- But you must know how the function works.
(2) Different Built-In Function?
- Python provides total of 69 built-in functions.
- Let’s discuss them one by one with examples.
(1) abs( )
Definition:
- The abs( ) function returns the absolute value of the specified number.
Syntax:
abs(n)
Parameter Values:
- n = Required. A number
Examples:
x = abs(-7.25)
y = abs(7+8j)
print(x)
print(y)
Output:
7.25
10.63014581273465
(2) any( )
Definition:
- The any() function returns True if any item in an iterable are True, otherwise it returns False.
- If the iterable object is empty, the any() function will return False.
- One (1) is considered as True.
Syntax:
any(iterable)
Parameter Values:
- iterable = An iterable object (list, tuple, dictionary)
Examples:
mylist1 = [True, True, True]
mylist2 = [0, 0, 1]
mylist3 = []
myset = {1, 1, 0}
mydict = {0 : "Subrat", 1 : "Abhipsa"}
print(any(mylist1))
print(any(mylist2))
print(any(mylist3))
print(any(myset))
print(any(mydict))
Output:
True
True
False
True
True
(4) ascii( )
Definition:
- The ascii( ) function returns a readable version of any object (Strings, Tuples, Lists, etc).
- The ascii( ) function will replace any non-ascii characters with escape characters:
- å will be replaced with \xe5.
Syntax:
ascii(object)
Parameter Values:
- object = An object, like String, List, Tuple, Dictionary etc.
Examples:
x = ascii("My name is Ståle")
y = ascii(1648789)
print(x)
print(y)
Output:
'My name is St\xe5le'
1648789
(5) bin( )
Definition:
- The bin( ) function returns the binary version of a specified integer.
- The result will always start with the prefix 0b.
Syntax:
bin(n)
Parameter Values:
- n = Required. An integer
Examples:
x = bin(36)
y = bin(111)
print(x)
print(y)
Output:
0b100100
0b1101111
(6) bool( )
Definition:
- The bool() function returns the Boolean value of a specified object.
- The object will always return True, unless:
- The object is empty, like [], (), {}
- The object is False
- The object is 0
- The object is None
Syntax:
bool(object)
Parameter Values:
- object = Any object, like String, List, Number etc.
Examples:
x = bool(123)
y = bool(0)
print(x)
print(y)
Output:
True
False
(7) bytearray( )
Definition:
- The bytearray() function returns a bytearray object.
- It can convert objects into bytearray objects, or create empty bytearray object of the specified size.
Syntax:
bytearray(x, encoding, error)
Parameter Values:
- x = A source to use when creating the bytearray object.
If it is an integer, an empty bytearray object of the specified size will be created.
If it is a String, make sure you specify the encoding of the source. - encoding = The encoding of the string
- error = Specifies what to do if the encoding fails.
Examples:
x = bytearray(4)
y = bytearray(10)
print(x)
print(y)
Output:
bytearray(b'\x00\x00\x00\x00')
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
(8) bytes( )
Definition:
- The bytes() function returns a bytes object.
- It can convert objects into bytes objects, or create empty bytes object of the specified size.
- The difference between bytes() and bytearray() is that bytes() returns an object that cannot be modified, and bytearray() returns an object that can be modified.
Syntax:
bytes(x, encoding, error)
Parameter Values:
- x = A source to use when creating the bytes object.
- If it is an integer, an empty bytes object of the specified size will be created.
- If it is a String, make sure you specify the encoding of the source.
- encoding = The encoding of the string
- error = Specifies what to do if the encoding fails.
Examples:
x = bytes(4)
y = bytes(10)
print(x)
print(y)
Output:
b'\x00\x00\x00\x00'
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
(9) callable( )
Definition:
- The callable() function returns True if the specified object is callable, otherwise it returns False.
Syntax:
callable(object)
Parameter Values:
object = The object you want to test if it is callable or not.
Examples:
def x():
a = 5
var = 87 # A Normal Variable Is Not Callable
print(callable(x))
print(callable(var))
Output:
True
False
(10) chr( )
Definition:
The chr() function returns the character that represents the specified unicode.
Syntax:
chr(number)
Parameter Values:
number = An integer representing a valid Unicode code point
Examples:
x = chr(97)
y = chr(5)
print(x)
print(y)
Output:
a
(11) classmethod()
Definition:
The classmethod() method returns a class method for the given function.
Syntax:
classmethod(function)
Parameter Values:
function = Function that needs to be converted into a class method
Examples:
class Student:
marks = 0
def compute_marks(self, obtained_marks):
marks = obtained_marks
print('Obtained Marks:', marks)
# convert compute_marks() to class method
Student.print_marks = classmethod(Student.compute_marks)
Student.print_marks(88)
Output:
Obtained Marks: 88
(12) compile()
Definition:
The compile() function returns the specified source as a code object, ready to be executed.
Syntax:
compile(source, filename, mode, flag, dont_inherit, optimize)
Parameter Values:
- source = Required. The source to compile, can be a String, a Bytes object, or an AST object
- filename = Required. The name of the file that the source comes from. If the source does not come from a file, you can write whatever you like.
- mode = Required. Legal values:
eval – if the source is a single expression
exec – if the source is a block of statements
single – if the source is a single interactive statement - flags = Optional. How to compile the source. Default 0
- dont-inherit = Optional. How to compile the source. Default False
- optimize = Optional. Defines the optimization level of the compiler. Default -1
Examples:
x = compile('print(55)', 'test', 'eval')
y = compile('print(55)\nprint(88)', 'test', 'exec')
exec(x)
exec(y)
Output:
55
55
88
(13) complex()
Definition:
The complex() function returns a complex number by specifying a real number and an imaginary number.
Syntax:
complex(real, imaginary)
Parameter Values:
- real = Required. A number representing the real part of the complex number. Default 0. The real number can also be a String, like this ‘3+5j’, when this is the case, the second parameter should be omitted.
- imaginary = Optional. A number representing the imaginary part of the complex number. Default 0.
Examples:
x = complex(3, 5)
y = complex('23+56j')
print(x)
print(y)
x = complex(3, 5)
y = complex('23+56j')
print(x)
print(y)
(14) complex()
Definition:
The delattr() function will delete the specified attribute from the specified object.
Syntax:
delattr(object, attribute)
Parameter Values:
- object = Required. An object.
- attribute = Required. The name of the attribute you want to remove
Examples:
class Person:
name = "John"
age = 36
country = "Norway"
delattr(Person, 'age') #Deleting Age Attribute
Person.age
Output:
AttributeError Traceback (most recent call last)
Input In [153], in <cell line: 1>()
----> 1 Person.age
AttributeError: type object 'Person' has no attribute 'age'
(15) getattr()
Definition:
The getattr() function returns the value of the specified attribute from the specified object.
Syntax:
getattr(object, attribute, default)
Parameter Values:
- object = Required. An object.
- attribute = The name of the attribute you want to get the value from.
- default = Optional. The value to return if the attribute does not exist.
Examples:
class Person:
name = "Abhispa"
age = 30
country = "India"
x = getattr(Person, 'age')
y = getattr(Person, 'country')
print(x)
print(y)
Output:
30
India
(16) hasattr()
Definition:
The hasattr() function returns True if the specified object has the specified attribute, otherwise False.
Syntax:
hasattr(object, attribute)
Parameter Values:
- object = Required. An object.
- attribute = The name of the attribute you want to check if exists
Examples:
class Person:
name = "Abhispa"
age = 30
country = "India"
x = hasattr(Person, 'name')
y = hasattr(Person, 'age')
print(x)
print(y)
Output:
True
True
(17) setattr()
Definition:
The setattr() function sets the value of the specified attribute of the specified object.
Syntax:
setattr(object, attribute, value)
Parameter Values:
- object = Required. An object.
- attribute = Required. The name of the attribute you want to set
- value = Required. The value you want to give the specified attribute
Examples:
class Person:
name = "John"
age = 36
country = "Norway"
setattr(Person, 'age', 40)
print(Person.age)
Output:
40
(18) dict()
Definition:
The dict() function creates a dictionary.
Syntax:
dict(keyword arguments)
Parameter Values:
- keyword arguments = Required. As many keyword arguments you like, separated by comma: key = value, key = value …
Examples:
x = dict(name = "Abhispa", age = 30, country = "India")
print(x)
Output:
{'name': 'Abhispa', 'age': 30, 'country': 'India'}
(19) dir()
Definition:
The dir() function returns all properties and methods of the specified object, without the values.
This function will return all the properties and methods, even built-in properties which are default for all object.
Syntax:
dir(object)
Parameter Values:
- object = The object you want to see the valid attributes of
Examples:
class Person:
name = "Abhispa"
age = 30
country = "India"
print(dir(Person))
Output:
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'country', 'name']
(20) divmod()
Definition:
- The divmod() function returns a tuple containing the quotient and the remainder when argument1 (dividend) is divided by argument2 (divisor).
Syntax:
divmod(dividend, divisor)
Parameter Values:
- dividend = A Number. The number you want to divide.
- divisor = A Number. The number you want to divide with.
Examples:
x = divmod(5, 2)
y = divmod(10, 5)
print(x)
print(y)
Output:
(2, 1)
(2, 0)
(21) enumerate()
Definition:
- The enumerate() function takes a collection (e.g. a tuple) and returns it as an enumerate object.
- The enumerate() function adds a counter as the key of the enumerate object.
Syntax:
enumerate(iterable, start)
Parameter Values:
- iterable = An iterable object.
- start = A Number. Defining the start number of the enumerate object. Default 0
Examples:
x = ('apple', 'banana', 'cherry')
y = enumerate(x)
for i in y:
print(i)
Output:
(0, 'apple')
(1, 'banana')
(2, 'cherry')
(22) eval()
Definition:
- The eval() function evaluates the specified expression, if the expression is a legal Python statement, it will be executed.
Syntax:
eval(expression, globals, locals)
Parameter Values:
- expression = A String, that will be evaluated as Python code
- globals = Optional. A dictionary containing global parameters
- locals = Optional. A dictionary containing local parameters
Examples:
x = 'print(55)'
y = '20 + 30'
eval(x)
eval(y)
Output:
55
50
(23) exec()
Definition:
- The exec() function executes the specified Python code.
- The exec() function accepts large blocks of code, unlike the eval() function which only accepts a single expression
Syntax:
exec(object, globals, locals)
Parameter Values:
- expression = A String, that will be evaluated as Python code
- globals = Optional. A dictionary containing global parameters
- locals = Optional. A dictionary containing local parameters
Examples:
x = 'name = "John"\nprint(name)'
y = 'sum = 20 + 30'
exec(x)
exec(y)
print(sum)
Output:
John
50
(24) filter()
Definition:
- The filter() function returns an iterator were the items are filtered through a function to test if the item is accepted or not.
Syntax:
filter(function, iterable)
Parameter Values:
- function = A Function to be run for each item in the iterable
- iterable = The iterable to be filtered
Examples:
ages = [5, 12, 17, 18, 24, 32]
def myFunc(x):
if x < 18:
return False
else:
return True
adults = filter(myFunc, ages)
for x in adults:
print(x)
Output:
18
24
32
(25) float()
Definition:
- The float() function converts the specified value into a floating point number.
Syntax:
float(value)
Parameter Values:
- value = A number or a string that can be converted into a floating point number.
Examples:
x = float(44)
y = float("45.543")
print(x)
print(y)
Output:
44.0
45.543
(26) format()
Definition:
- The format() function formats a specified value into a specified format.
Syntax:
format(value, format)
Parameter Values:
- value= A value of any format
- format = The format you want to format the value into.
Legal values:
‘<‘ – Left aligns the result (within the available space)
‘>’ – Right aligns the result (within the available space)
‘^’ – Center aligns the result (within the available space)
‘=’ – Places the sign to the left most position
‘+’ – Use a plus sign to indicate if the result is positive or negative
‘-‘ – Use a minus sign for negative values only
‘ ‘ – Use a leading space for positive numbers
‘,’ – Use a comma as a thousand separator
‘_’ – Use a underscore as a thousand separator
‘b’ – Binary format
‘c’ – Converts the value into the corresponding unicode character
‘d’ – Decimal format
‘e’ – Scientific format, with a lower case e
‘E’ – Scientific format, with an upper case E
‘f’ – Fix point number format
‘F’ – Fix point number format, upper case
‘g’ – General format
‘G’ – General format (using a upper case E for scientific notations)
‘o’ – Octal format
‘x’ – Hex format, lower case
‘X’ – Hex format, upper case
‘n’ – Number format
‘%’ – Percentage format
Examples:
# Format the number 0.5 into a percentage value:
x = format(0.5, '%')
#Format 255 into a hexadecimal value.
y = format(255, 'x')
#Format 4 into a binary value.
z = format(4,'b')
print(x)
print(y)
print(z)
Output:
50.000000%
ff
100
(27) frozenset()
Definition:
- The frozenset() function returns an unchangeable frozenset object (which is like a set object, only unchangeable).
Syntax:
frozenset(iterable)
Parameter Values:
- iterable= An iterable object, like list, set, tuple etc.
Examples:
mylist = ['apple', 'banana', 'cherry']
x = frozenset(mylist)
x[1] = "strawberry"
Output:
TypeError Traceback (most recent call last)
Input In [205], in <cell line: 3>()
1 mylist = ['apple', 'banana', 'cherry']
2 x = frozenset(mylist)
----> 3 x[1] = "strawberry"
TypeError: 'frozenset' object does not support item assignment
(28) globals()
Definition:
- The globals() function returns the global symbol table as a dictionary.
- A symbol table contains necessary information about the current program.
Syntax:
globals()
Parameter Values:
- No parameters
Examples:
k = globals()
print(k)
{'__name__': '__main__', '__doc__': 'Automatically created module for IPython interactive environment', '__package__': None, '__loader__': None, '__spec__': None, '__builtin__': <module 'builtins' (built-in)>, '__builtins__': <module 'builtins' (built-in)>, '_ih': ['', 'k = globals()', 'print(k)'], '_oh': {}, '_dh': [WindowsPath('C:/Users/SuSahoo/Blogs')], 'In': ['', 'k = globals()', 'print(k)'], 'Out': {}, 'get_ipython': <bound method InteractiveShell.get_ipython of <ipykernel.zmqshell.ZMQInteractiveShell object at 0x000001CA46595340>>, 'exit': <IPython.core.autocall.ZMQExitAutocall object at 0x000001CA465958B0>, 'quit': <IPython.core.autocall.ZMQExitAutocall object at 0x000001CA465958B0>, '_': '', '__': '', '___': '', '_i': 'k = globals()', '_ii': '', '_iii': '', '_i1': 'k = globals()', 'k': {...}, '_i2': 'print(k)'}
(29) hash()
Definition:
- The hash() method returns the hash value of an object if it has one.
- Hash values are just integers that are used to compare dictionary keys during a dictionary look quickly.
Syntax:
hash(object)
Parameter Values:
- object = The object whose hash value is to be returned (integer, string, float)
Examples:
# hash for integer unchanged
print('Hash for 181 is:', hash(181))
# hash for decimal
print('Hash for 181.23 is:',hash(181.23))
# hash for string
print('Hash for Python is:', hash('Python'))
Output:
Hash for 181 is: 181
Hash for 181.23 is: 530343892119126197
Hash for Python is: 3481074319066699869
(30) help()
Definition:
- The help() method calls the built-in Python help system.
Syntax:
help(object)
Parameter Values:
- object (optional) = you want to generate the help of the given object.
Examples:
help(list)
help(dict)
help(print)
help([1, 2, 3])
Output:
'My name is St\xe5le'
1648789
(31) hex()
Definition:
- The hex() function converts the specified number into a hexadecimal value.
- The returned string always starts with the prefix 0x.
Syntax:
hex(number)
Parameter Values:
- number = An Integer.
Examples:
x = hex(255)
y = hex(1)
print(x)
print(y)
Output:
0xff
0x1
(32) id()
Definition:
- The id() function returns a unique id for the specified object.
- All objects in Python has its own unique id.
- The id is assigned to the object when it is created.
- The id is the object’s memory address, and will be different for each time you run the program. (except for some object that has a constant unique id, like integers from -5 to 256)
Syntax:
id(object)
Parameter Values:
- object = An object, like String, List, Tuple, Dictionary etc.
Examples:
x = ('apple', 'banana', 'cherry')
y = [1,2,3,4,5]
print(id(x))
print(id(y))
Output:
2064099404416
2064098945344
(33) input()
Definition:
- The input() function allows user to input some value.
Syntax:
input(prompt)
Parameter Values:
- object = An object, like String, List, Tuple, Dictionary etc..
Examples:
x = input('Enter your name:')
print('Hello, ' + x)
Output:
Enter your name:Abhispa
Hello, Abhispa
(34) int()
Definition:
- The int() function converts the specified value into an integer number.
Syntax:
int(value, base)
Parameter Values:
- value = A number or a string that can be converted into an integer number.
- base = A number representing the number format. Default value: 10
Examples:
x = int("78")
y = int("87")
print(x)
print(y)
Output:
78
87
(35) isinstance()
Definition:
- The isinstance() function returns True if the specified object is of the specified type, otherwise False.
- If the type parameter is a tuple, this function will return True if the object is one of the types in the tuple.
Syntax:
isinstance(object, type)
Parameter Values:
- object = Required, An object, like String, List, Tuple, Dictionary etc.
- type = A type or a class, or a tuple of types and/or classes
Examples:
x = isinstance(5, int)
y = isinstance("Hello", (float, int, str, list, dict, tuple))
print(x)
print(y)
Output:
True
True
(36) issubclass()
Definition:
- The issubclass( ) function returns True if the specified object is a subclass of the specified object, otherwise False.
Syntax:
issubclass(object, subclass)
Parameter Values:
- object = Required , An object, like String, List, Tuple, Dictionary etc.
- subclass = A class object, or a tuple of class objects
Examples:
class myAge:
age = 36
class myObj(myAge):
name = "John"
age = myAge
x = issubclass(myObj, myAge)
print(x)
Output:
True
(37) iter()
Definition:
- The iter( ) function returns an iterator object.
Syntax:
iter(object, sentinel)
Parameter Values:
- object =Required. An iterable object
- sentinel = Optional. If the object is a callable object the iteration will stop when the returned value is the same as the sentinel
Examples:
x = iter(["apple", "banana", "cherry"])
print(next(x))
print(next(x))
print(next(x))
Output:
apple
banana
cherry
(38) len()
Definition:
- The len() function returns the number of items in an object.
- When the object is a string, the len() function returns the number of characters in the string.
Syntax:
len(object)
Parameter Values:
- object = Required. An object. Must be a sequence or a collection
Examples:
x = ["apple", "banana", "cherry"]
y = "Hello"
print(len(x))
print(len(y))
Output:
3
5
(39) list()
Definition:
- The list( ) function creates a list object.
- A list object is a collection which is ordered and changeable.
Syntax:
list(iterable)
Parameter Values:
- iterable= Required. A sequence, collection or an iterator object
Examples:
x = list(('apple', 'banana', 'cherry'))
y = list('Abhispa')
print(x)
print(y)
Output:
['apple', 'banana', 'cherry']
['A', 'b', 'h', 'i', 's', 'p', 'a']
(40) locals()
Definition:
- The locals() function returns the local symbol table as a dictionary.
- A symbol table contains necessary information about the current program.
Syntax:
locals()
Parameter Values:
- No parameters
Examples:
x = locals()
print(x["__name__"])
Output:
__main__
(41) map()
Definition:
- The map() function executes a specified function for each item in an iterable.
- The item is sent to the function as a parameter.
Syntax:
map(function, iterables)
Parameter Values:
- function = Required. The function to execute for each item.
- iterable = Required. A sequence, collection or an iterator object. You can send as many iterables as you like, just make sure the function has one parameter for each iterable.
Examples:
def myfunc(n):
return len(n)
x = map(myfunc, ('apple', 'banana', 'cherry'))
for i in x:
print(i)
Output:
5
6
6
(42) max()
Definition:
- The max() function returns the item with the highest value, or the item with the highest value in an iterable.
- If the values are strings, an alphabetically comparison is done.
Syntax:
max(n1, n2, n3, ...)
Parameter Values:
- n1, n2, n3, … = One or more items to compare
Examples:
x = ascii("My name is Ståle")
y = ascii(1648789)
print(x)
print(y)
Output:
10
7
(43) memoryview()
Definition:
- The memoryview( ) function returns a memory view object from a specified object.
Syntax:
memoryview(obj)
Parameter Values:
- obj = A Bytes object or a Bytearray object.
Examples:
x = memoryview(b"Abhispa")
print(x)
#return the Unicode of the first character
print(x[0])
#return the Unicode of the second character
print(x[1])
Output:
<memory at 0x000001E095CA31C0>
65
98
(44) min()
Definition:
- The min( ) function returns the item with the lowest value, or the item with the lowest value in an iterable.
- If the values are strings, an alphabetically comparison is done.
Syntax:
min(n1, n2, n3, ...)
Parameter Values:
- n1, n2, n3, … = One or more items to compare.
Examples:
x = min("Subrat", "Abhispa", "Arpita")
y = min(1, 5, 3, 9)
print(x)
print(y)
Output:
Abhispa
1
(45) next()
Definition:
- The next( ) function returns the next item in an iterator.
- You can add a default return value, to return if the iterable has reached to its end.
Syntax:
next(iterable, default)
Parameter Values:
- iterable = Required. An iterable object.
- default = Optional. An default value to return if the iterable has reached to its end.
Examples:
mylist = iter(["Subrat", "Abhispa", "Arpita"])
x = next(mylist)
print(x)
x = next(mylist)
print(x)
x = next(mylist)
print(x)
Output:
Subrat
Abhispa
Arpita
(46) object()
Definition:
- The object( ) function returns an empty object.
- You cannot add new properties or methods to this object.
- This object is the base for all classes, it holds the built-in properties and methods which are default for all classes.
Syntax:
object()
Parameter Values:
- No parameters
Examples:
x = object()
print(x)
x = object()
print(x)
(47) oct()
Definition:
- The oct( ) function converts an integer into an octal string.
- Octal strings in Python are prefixed with 0o.
Syntax:
oct(int)
Parameter Values:
- int = An Integer Number.
Examples:
x = oct(12)
print(x)
Output:
0o14
(48) open()
Definition:
- The open() function opens a file, and returns it as a file object.
Syntax:
open(file, mode)
Parameter Values:
- file = The path and name of the file.
- mode = A string, define which mode you want to open the file in:
“r” – Read – Default value. Opens a file for reading, error if the file does not exist
“a” – Append – Opens a file for appending, creates the file if it does not exist
“w” – Write – Opens a file for writing, creates the file if it does not exist
“x” – Create – Creates the specified file, returns an error if the file exist
In addition you can specify if the file should be handled as binary or text mode
“t” – Text – Default value. Text mode
“b” – Binary – Binary mode (e.g. images)
Examples:
f = open("E:/Blogs/Python/demofile.txt", "r")
print(f.read())
My Name Is Subrat Kumar Sahoo
I Am From India
I Likes To Write Blogs
(49) ord()
Definition:
- The ord() function returns the number representing the Unicode code of a specified character.
Syntax:
ord(character)
Parameter Values:
- character = String, any character
Examples:
x = ord("A")
print(x)
Output:
65
(50) pow()
Definition:
- The pow() function returns the value of x to the power of y (xy).
- If a third parameter is present, it returns x to the power of y, modulus z.
Syntax:
pow(x, y, z)
Parameter Values:
- x = A number, the base.
- y = A number, the exponent
- z = Optional. A number, the modulus
Examples:
x = pow(4, 3) #(same as 4 * 4 * 4):
y = pow(4, 3, 5) #(same as (4 * 4 * 4) % 5)
print(x)
print(y)
Output:
64
4
(51) print()
Definition:
- The print() function prints the specified message to the screen, or other standard output device.
- The message can be a string, or any other object, the object will be converted into a string before written to the screen.
Syntax:
print(object(s), sep=separator, end=end, file=file, flush=flush)
Parameter Values:
- object(s) Any object, and as many as you like. Will be converted to string before printed
- sep=‘separator’ Optional. Specify how to separate the objects, if there is more than one. Default is ‘ ‘
- end=‘end’ Optional. Specify what to print at the end. Default is ‘\n’ (line feed)
- file Optional. An object with a write method. Default is sys.stdout
- flush Optional. A Boolean, specifying if the output is flushed (True) or buffered (False). Default is False
Examples:
print("Hello World")
print("Hello", "how are you?")
x = ("Subrat", "Abhispa", "Arpita")
print(x)
print("Hello", "how are you?", sep="---")
Output:
Hello World
Hello how are you?
('Subrat', 'Abhispa', 'Arpita')
Hello---how are you?
(52) property()
Definition:
- Python property() function returns the object of the property class and it is used to create property of a class.
Syntax:
property(fget, fset, fdel, doc)
Parameter Values:
- fget() – used to get the value of attribute
- fset() – used to set the value of attribute
- fdel() – used to delete the attribute value
- doc() – string that contains the documentation (docstring) for the attribute
- Return: Returns a property attribute from the given getter, setter and deleter.
Examples:
# Python program to explain property() function
# Alphabet class
class Alphabet:
def __init__(self, value):
self._value = value
# getting the values
def getValue(self):
print('Getting value')
return self._value
# setting the values
def setValue(self, value):
print('Setting value to ' + value)
self._value = value
# deleting the values
def delValue(self):
print('Deleting value')
del self._value
value = property(getValue, setValue,
delValue, )
# passing the value
x = Alphabet('Praudyog')
print(x.value)
x.value = 'GfG'
del x.value
Output:
Getting value
Praudyog
Setting value to GfG
Deleting value
(53) range()
Definition:
- The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.
Syntax:
range(start, stop, step)
Parameter Values:
- start = Optional. An integer number specifying at which position to start. Default is 0.
- stop = Required. An integer number specifying at which position to stop (not included).
- step = Optional. An integer number specifying the incrementation. Default is 1
Examples:
x = range(3, 10, 2)
for n in x:
print(n)
Output:
3
5
7
9
(54) repr()
Definition:
- The repr( ) returns a readable version of an object.
- Basically it converts any object to string type to print.
Syntax:
repr(obj)
Parameter Values:
- obj = The object whose printable representation has to be returned
Examples:
numbers = [1, 2, 3, 4, 5]
# create a printable representation of the list
printable_numbers = repr(numbers)
print(printable_numbers)
print(type(printable_numbers))
Output:
[1, 2, 3, 4, 5]
<class 'str'>
(49) ord()
Definition:
- The ord() function returns the number representing the Unicode code of a specified character.
Syntax:
ord(character)
Parameter Values:
- character = String, any character
Examples:
x = ord("A")
print(x)
Output:
65
(49) ord()
Definition:
- The ord() function returns the number representing the Unicode code of a specified character.
Syntax:
ord(character)
Parameter Values:
- character = String, any character
Examples:
x = ord("A")
print(x)
Output:
65
(49) ord()
Definition:
- The ord() function returns the number representing the Unicode code of a specified character.
Syntax:
ord(character)
Parameter Values:
- character = String, any character
Examples:
x = ord("A")
print(x)
Output:
65
(49) ord()
Definition:
- The ord() function returns the number representing the Unicode code of a specified character.
Syntax:
ord(character)
Parameter Values:
- character = String, any character
Examples:
x = ord("A")
print(x)
Output:
65
(49) ord()
Definition:
- The ord() function returns the number representing the Unicode code of a specified character.
Syntax:
ord(character)
Parameter Values:
- character = String, any character
Examples:
x = ord("A")
print(x)
Output:
65
(49) ord()
Definition:
- The ord() function returns the number representing the Unicode code of a specified character.
Syntax:
ord(character)
Parameter Values:
- character = String, any character
Examples:
x = ord("A")
print(x)
Output:
65
(49) ord()
Definition:
- The ord() function returns the number representing the Unicode code of a specified character.
Syntax:
ord(character)
Parameter Values:
- character = String, any character
Examples:
x = ord("A")
print(x)
Output:
65
(49) ord()
Definition:
- The ord() function returns the number representing the Unicode code of a specified character.
Syntax:
ord(character)
Parameter Values:
- character = String, any character
Examples:
x = ord("A")
print(x)
Output:
65
(49) ord()
Definition:
- The ord() function returns the number representing the Unicode code of a specified character.
Syntax:
ord(character)
Parameter Values:
- character = String, any character
Examples:
x = ord("A")
print(x)
Output:
65
(49) ord()
Definition:
- The ord() function returns the number representing the Unicode code of a specified character.
Syntax:
ord(character)
Parameter Values:
- character = String, any character
Examples:
x = ord("A")
print(x)
Output:
65