DEV Community

Mohit Raj
Mohit Raj

Posted on

3.2 How to take User input in python

User input

  1. Developers often have a need to interact with users, either to get data or to provide some sort of result.
  2. When you write a program sometime we need to give input from keyboard or any input device.
  3. Python provides us with two inbuilt functions to read the input from the keyboard.

a). raw_input(prompt)
b). input(prompt)

raw_input() function

  1. This function works in older version (like Python 2.x). This function takes exactly what is typed from the keyboard, convert it to string and then return it to the variable in which we want to store.
  2. If you entered any number then these numbers also converted into string.

input() function

  1. This function first takes the input from the user and then evaluates the expression, which means Python automatically identifies whether user entered a string or a number or list.
  2. If the input provided is not correct then either syntax error or exception is raised by python.
  3. Example : x=input("What is your name: ") Here, 'x' is a variable which will get the value, typed by user during the execution of program.
  4. command written in the double or single quotes inside the input function is printed as it is on the screen as shown below.Alt TextHere you can see that program will print 'What is your name:' and waiting for the user to input the value.
  5. Program execuation will stop until user not given any inputAlt Text Here user enter the name. And this name value is stored in the variable 'x'.
  6. After giving the input hit enter button so that program continue their execution.
  7. Let's check whether x assigned the same value (user input) or not for this we use print function. Example : print(x) and we get the same output that the user input.Alt Text

This is this simple way to take input from the user directly. you may take a list as an input. these all are discussed in upcoming posts.

If you have any problem regarding any topic till discussed in this series please let me known in the comment box.

Thank You.....

Oldest comments (0)