Read Python Interview Questions and Answers for Beginners and Experienced

Python chr() function

Python chr() is another one of Python built-in functions. In this post of Python tutorial for beginners, we will learn the use of chr() function with example.

 

Introduction to Python chr() function

In simple term, chr() function take the ASCII integer value and return the character corresponding to ASCII number.

 

Syntax of chr()

chr(ASCII_number)

 

  • chr() is function name.
  • ASCII_number is ASCII integer value.
  • In Python ASCII number can range from 0 to 1,1141,111

 

Example of chr()

Let’s understand chr() function by taking example.


#Python chr() function example

for i in range (50):

   print (chr(i))
 

 

Output



















!
"
#
$
%
&
'
(
)
*
+
,
-
.
/
0
1
  • In above example, we loop the variable i till 50.
  • print(chr(i)) will display all the ASCII code value who has value between 50.
  • chr() function only display value of ASCII code between 0, 1,1141,111. (with base 16)
  • if we provide input other than ASCII code, chr() function will throw out of range error.

 

chr() function out of range example

Let’s see if we provide value out of range to chr() function. Let’s say we provide negative integer value.


#Python chr() function example

print (chr(-45))
 
 

 

Output

ValueError: chr() arg not in range(0x110000)
  • if we provide any value which is not ASCII value , it will throw not in range error.

 

If we provide input other than integer then also it will throw error saying not an Integer value


#Python chr() function example

print (chr(8.9))
 
 

 

Output

TypeError: integer argument expected, got float

 

  • If we provide any other value, say we put float value , then it throws error that integer argument expected, got float

It means chr() function takes only integer value which is in ASCII range.