Reading Keyboard Input in Python

PythonServer Side ProgrammingProgramming

Python provides two built-in functions to read a line of text from standard input, which by default comes from the keyboard. These functions are −

  • raw_input
  • input

The raw_input Function

The raw_input([prompt]) function reads one line from standard input and returns it as a string (removing the trailing newline).

str = raw_input("Enter your input: ")
print "Received input is : ", str

This prompts you to enter any string and it would display same string on the screen. When I typed "Hello Python!", its output is like this −

Enter your input: Hello Python
Received input is : Hello Python

The input Function

The input([prompt]) function is equivalent to raw_input, except that it assumes the input is a valid Python expression and returns the evaluated result to you.

str = input("Enter your input: ")
print "Received input is : ", str

This would produce the following result against the entered input −

Enter your input: [x*5 for x in range(2,10,2)]
Recieved input is : [10, 20, 30, 40]
Published on 30-Jan-2020 11:05:29