Last Updated:

ord()  | Other built-in Python functions

Ord is a function (short of ordinal) that returns an integer representing the character passed to it. This means that each character has some integer value, these characters cannot be read by the computer directly, it first converts each character into ASCII code.

Python provides us with an ord function to generate ASCII code for any character, and it will be an integer. the ord function accepts only one character. You can pass this single character in either single quotation marks or double quotation marks. You can also pass a string value inside the ord function, but the string length must be 1, or the ord function will return an error.

ASCII is an encoding standard that assigns an integer value to each character on a keyboard. Each symbol has its own integer value. The result will be different for both uppercase and lowercase characters.

 

Syntax:

ord(character)

Examples of ord functions in Python

In this article, we will discuss the ord function in python with a few examples.

Example No 1

Code:
x = 'a'
print(ord(x))

Output:
97

As you can see in the above code, we've passed 'a' to the ord function.

Example No. 2

Code:
x = 'A'
print(ord(x))

Output:
65

So, from the example above, you can see that the program returned an integer value, this integer value is an ASCII code for "A", that is, the capital letter A. Here we should note an important point: when we talk about ASCII code, then A != a. This means that the capital alphabet is not equal to a small alphabet. They both have their own ASCII codes.

Example No 3

The code:
x="A"
print(ord(x))

output:
65

In the above program, we have the capital letter A in double quotation marks, so its length string and the ord function will accept and return the same integer value.

Example No 4

The code:
x = "ab"
print(ord(x))

Exit:
Traceback (most recent call last):
File"main.py", line 2, in <module>
print ord((x))
Type error:ord() expected a character, but string of length 2 found

As you can see, this time we have "Ab", its string, but the string length is 2, and the ord function expected a line length of 1.

Example No 5

The code :
x = «1»
print(ord(x))
Exit:
49

In the example above, we can see that I used an integer value, which is 1 in single quotation marks, so when we use double quotation marks, it's a string, so now 1 is a string of length, and we get the desired result.

Example No 6

Code:
x = ‘1’
print(ord(x))

Output:
49

In the example above, we used 1 in one quotation mark, so now it's a character.so the ord function will execute it successfully and we'll get the desired result.

Example No 7

Code:
x = 1
print(ord(x))

Exit:
Traceback (most recent call last):
File»main.py»,line 2, in <module>
print ord((x))
Type error:ord() expected a character, but string of length 2 found

In the example above, we have the same value as the previous code, and this time we directly used 1 inside the ord function, but the ord function will not execute it because it expects a character or string of length 1, and the ord function will return an error.

Example No 8

Code:
x = »
print(ord(x))

Output:
32

In the above program, you may be wondering that we mentioned a blank character and the organization's features still work, but it's not empty, it's one space. A single space is also a character in an ASCII diagram and its value is 32. A space is the first character in an ASCII diagram.

Example No 9

Code:
x = ‘#’
print(ord(x))

Output:
35

In the example above, we used a special character, and the ord function will also work for the special character.

Example No 10

Code:
x = ‘.’
print(ord(x))

Output:
46

In the example above, I have '.' as input to the ord function, and we get the expected result.

Key thoughts on the ord() function

The Ord function takes a single character or a string of 1 as input and returns an integer, which is the equivalent ASCII code. The computer understands only these ASCII codes, the ASCII codes are converted into binary code, which is used by the computer to process the information.

Built-in Python functions – learn functions with syntax and examples

 

You've already used some built-in Python functions, such as the print() function used to output a string to the console. At the moment, the latest version of Python 3.8 has 69 built-in functions.
We'll go through each of them.

The Python interpreter contains a number of functions that are always available for use anywhere in the program. Below is a list of all available built-in features in chronological order.

Table of built-in Python functions

Table of built-in Python functions

Here's a detailed explanation of the built-in functions in Python.

abs(x)

The abs() function returns the absolute value of a number that is the distance of a point from the zero index. The x argument can be an integer or a floating-point value. In the case of complex numbers, their value is returned.

Code:
print( abs(4) )
print( abs(-2.5) )
print( abs(3j + 2) )

Release:
4
2.5
3.6055512754639896

all(iterable)

The all() function takes an iterative container as an argument and returns True when all elements in the iterative container are True (or empty), otherwise it returns False.

Code:
print( все([]))
print( all([True, True, False]))
print(all({1,3,5,2}))

Exit:

True
False
True

any(iterable)

The any() function takes an iterative container as an argument and returns True when one of the elements inside the iterative container is True, otherwise it returns False.

Code:
print( any([]) )
print( any([False, False, True, 1, 3]) )
print(any({10,20,30,40}) )

Exit:
False
True
True

ascii(object )

The ascii() function returns a printed representation of an object. It escapes non-ASCII characters in a string. The string returned by ascii() is similar to the repr() function in Python2.

Code:

ascii(2020)
ascii(‘a’)
ascii(‘Привет\nМир’)

Release:
'2020'
"'a'"
"Hi \\n World""

bin(x)

The bin() function converts an integer to its binary representation in string format. Binary numbers have the prefix "0b". It only accepts integers, and assigning a function a string or float value will result in an error.

Code:
thousand(12) thousand(-12)

Output:
'0b1100'
'-0b1100'

bool([x])

The bool() function returns True or False by converting the argument to a Boolean value. It returns True when the passed argument is True, otherwise empty containers and a false value will return False.

Code:
bool(False)
bool([])
bool(20)
bool({1,2,4})

Exit:
False
False
True
True

breakpoint(*args, **kws)

Thebreakpoint() function is introduced from Python 3.7 and helps with debugging. For example, when you use the pdb debugger, you call pdb.set_trace() in your code. Then, for a machine that has a web-pdb debugger, you will have to change the code to the web-pdb.set_trace () method. This becomes an overhead, and for this we have a breakpoint() method that allows us to write loosely bound debug code.

Code:
msg = breakpoint "Hello"

()

Exit:
> c:\users\Techvidvan\appdata\local\programs\python\python37-32\bp.py
(4)<module>()
->print(msg)
(Pdb) msg
‘Привет’
(Pdb)

bytearray([source[, encoding[, errors]]])

It returns a variable version of the byte array of integers ranging from 0 to 256. If an integer is passed, it returns us an array of this size with zero bytes. If a string is passed, you must provide encoding in the second argument.

Code:

bytearray(4)
bytearray(‘abc’,’utf-8′)
bytearray([1,2,3])

Exit:
bytearray(b'x00\x00\x00\x00′)
bytearray(b ' abc')
bytearray(b'x01\x02\x03')

bytes([source[, encoding[, errors]]])

The byte() function is similar to the bytearray() function. The only difference is that the bytes() function returns an immutable object. We cannot change the elements of the bytes function.

Code:
bytes(3)
bytes([3,2,1])

Exit:
b’\x00\x00\x00′
b’\x03\x02\x01′

callable(object)

The function being called tells us whether the object is being called or not. It returns True when the passed argument is invoked, otherwise it returns False. User-defined and all built-in functions are callable.

Code:

callable(print)
callable([1,2,3])
callable(abs)

Exit:
True
False
True

chr(i)

The chr() function is an inverse ord() function. It takes a unicode code point as an argument and returns a string representation of the character. The input range is from 0 to 1,114,111. Outside of this range, it will cause an error.

Code:
chr(65)
chr(120)

Output:
'A'
'x'

@classmethod()

@classmethod is a decorator that is used to create class methods that will be passed to all objects in the same way that self is passed.

Syntax:

@classmethod()
deffunc(cls, args…):

Code:

class Person:
@classmethod
defdisplay(cls):
print(«Возраст человека-42 года»)
Person.display()

Output:
Human age -42 years

compile(source, file name, mode)

Compile() functions compile source code into an executable object. The object can be executed using the exec() or eval() functions. The first parameter is the source code, the second is the file name, and the third is the mode.

Code:
exec(compile(‘num1=10;num2=20;print(num1+num2);’,», ‘exec’))

Output:
30

complex([real[, imag]])

The complex() function returns or converts a number to a complex number. The first argument is the actual part of the complex number, and the second argument (optional) is the imaginary part.

Code:

complex(1,2)
complex(5,5)
complex(3+7j)

Exit:
(1+2d)
(5.5+0d)
(3+7d)

delattr(object, name)

The delattr() function is used to remove an attribute of an object. It takes two arguments: the object you want to remove from and the attribute name you want to remove. You can delete an attribute only when you have permission to do so.

Code:
classcar:
color = ‘Синий’
c = Car()
print(c.color)
delattr(c, ‘color’)
print(c.color)

Exit:
Синий
Traceback (most recent call last):
File “C:/Users/Techvidvan/AppData/Local/Programs/Python/Python37-32/bp.py”, line 6, in <module>
delattr(c, ‘color’)
AttributeError: Синий

dictate()

The dict() function returns or creates a new dictionary that is useful when mapping values.
This requires iteration.

Code:
Numbers1 = dict(a=1, b=2, c=3, d=4)
Numbers2 = dict([(‘a’, 1), (‘b’: 2), (‘c’:3), (‘d’:4) ])
print(Numbers 1)
print(Numbers2)

Exit:
{'a': 1, 'b': 2, 'c':3, 'd':4 }
{'a': 1, 'b': 2, 'c':3, 'd':4 }

dir. ([object])

The dir() object returns a list of all the names of the current local scope if no argument is passed.

Code:
Variable1 = 10
Variable2 = 'Hey'
dir. ()

Output:
['Variable1', 'Variable2', '__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']

When we pass an object as an argument, it returns a list of all valid attribute names for that object. Let's look at the string attributes.

Code:
you. (str)

Exit:

[‘__add__’, ‘__class__’, ‘__contains__’, ‘__delattr__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__ge__’,’__format__’, ‘__getattribute__’, ‘__getitem__’, ‘__getnewargs__’, ‘__gt__’, ‘__hash__’, » __init__», » __init_подкласс__», » __iter__», » __le__», » __len__», » __lt__», » __mod__», » __mul__», » __ne__», » __new__», » __reduce__», » __repr__», » __reduce_ex__», » __rmod__», » __rmul__‘,’ __setattr__‘,’ __sizeof__‘,’ __str__‘,’ __subclasshook__‘,’ capitalize‘,’ casefold‘,’ center‘,’ count‘,’ encode‘,’ endswith‘,’ expandtabs‘,’ find‘,’ format‘,’ format_map‘,’ index‘,’ isalnum‘,’ isdecimal‘,’ isalpha‘,’ исдигит ‘, «isidentifier», «islower», «isnumeric», «isprintable», «isspace», «istitle», «isupper», «join», «lstrip», «ljust», «lower», «maketrans», «partition», «replace», «rfind», «rindex», «rjust», «rpartition», «rsplit», «rstrip», «split», «splitlines», «startswith», ‘strip’, ‘swapcase’, ‘title’, ‘translate’, ‘upper’, ‘zfill’]

divmod(a,b)

The divmod() function takes two integers or floating numbers as arguments, and then returns a tuple whose first element is a private and the second is a remainder.

Code:
divmod(20,2)
divmod(48,5)
divmod(11,2.5)

Output:
(10, 0)
(9, 3)
(4.0, 1.0)

enumerate(итеративное, start=0)

The function returns us an enumerate object, which is used in loops to iterate through iterative objects. This is useful when we want to have a counter to calculate something. Numbers start at zero, if you want to start with another number, then you can specify this in the second argument.

Code:
for i, country in enumerate([‘США’, ‘ВЕЛИКОБРИТАНИЯ’, ‘Нью-ЙОРК’, ‘ТКИ]):
print(i, страна)

Output:
0 US
1 UK
2 NEW YORK
3 TCI

eval()

The eval() function evaluates a Python expression that is passed as a string. It parses a Python expression and then the function evaluates it.

Code:
x=5
eval(‘10<20’)
eval(‘x+ 10’)

Exit:
True
15

exec()

The exec() function is used to dynamically execute Python code. We can write Python code as a string and pass it as an argument to the exec() function. It will parse the string and execute the Python code inside it.

Code:

exec(‘print(“Привет”)’)
exec(‘a=20;b=30; print(a*b)’)

Output:
Hi 600

filter(function, iterative)

The filter function is used to filter the data. It does this by repeating the second iterative argument, and the first argument is a function that decides how we will filter the elements. This is mainly used with lambda expressions.

Code:
list(filter(lambda x:x>5 ,[1,2,3,4,5,6,8,10]))

Output:
[6,8,10]

Here we used lambda, a function in which we need items greater than 5, and the list is filtered out of items less than or equal to 5.

float([x])

Float functions return or convert an argument to a floating-point value, if it is compatible. We can convert integers and strings containing only numbers.

Code:
float(45)
float(‘12’)

Release:
45.0
12.0

A complex number or a string with other characters, such as alphabets, will cause an error.

format(value[, format_spec])

The format() function is similar to the format method in strings. It is used to change the value according to a specific format. The first argument is the value to be formatted, and the second argument is a specifier of how the value is set.

Code:
#формат a decimal number to a binary
format ( 24, "b")
#отформатируйте a floating-point value so that it consists of two decimal digits.
format(123.456, “0.2 f” )

Output:
'11000'
'123.46'

frozenset([iterable])

The frozenset() function takes an iteration as an argument and converts it to an immutable set. Sets are changeable by default. If we need the same set properties, but in an immutable object, then we use frozenset.

Code:
frozenset({1,2,3,4})
frozenset([30, 20, 10])
frozenset((1, 2.5, 8.5, 4))

Output:
frozenset({1, 2, 3, 4, 5})
frozenset({10, 20, 30})
frozenset({8.5, 1, 2.5, 4})

getattr(object, name)

The getattr() function is used to get the value of an attribute of an object. The first argument is the object from which you want to get the value, and the second argument is a string that represents the attribute name.

Code:
classcar:
color = ‘Синий’
c = Car()
print(getattr(c, ‘color’) )

Output:
Blue

globals()

The function returns a dictionary in which all global objects are available in the current scope or module. Let's create a list in the global scope and look at the object dictionary in the global scope.

Code:
list1=[1,2,3,4]
globals()

Exit:
{‘__name__’: ‘__main__’, ‘__doc__’:None, ‘__package__’: None, ‘__loader__’: <class ‘_frozen_importlib. BuiltinImporter’>, ‘__spec__’: None, ‘__аннотации__’: {}, ‘__builtins__’: <модуль ‘builtins’ (встроенный)>, ‘Car’: <класс ‘__main__. Car’>, ‘c’: <__main__.Объект Car по адресу 0x03A79208>, ‘list1’: [1, 2, 3, 4]}

hasattr(object, name)

This function is also similar to the getattr() function, instead checking whether the object contains the specified attribute or not. It returns a Boolean value.

Code:
classcar:
color= “Green”
c= Car()
print(hasattr(c, “color”))
print(hasattr(c, “price”))

Exit:
True
False

hash(object)

In Python, everything is an object, numbers, strings, etc. they are all an object. Hashed objects are mapped to an integer value in Python. The hash() function returns us a hash of the specified object.

Code:
print( hash(45) )
print( hash(“hello”) )
print( hash(94387593420) )
print( hash(True )
print(hash(2.5))

Output:
45
-1010369850
2045796599
1
1073741826

Conclusion

This article is a bit long and you should congratulate yourself on going this far. We discussed 29 built-in Python functions. Built-in functions are available for use anywhere in a Python program.