How To Get Input From Keyboard with Python raw_input with Examples


Python provides different functions and methods in order to get input from user, system, network etc. raw_inputis a method used to get input from user from interactive shell. We will look different use cases for raw_input for python.

Syntax

The syntax of the raw_input changes according to python version. We will look for both of them but use Python 3 version in the examples.

Python 2

DATA = raw_input('PROMPT')
  • DATA is set to the provided data
  • PROMPT is the text which will shown during data input

Python 3

DATA = input('PROMPT')
  • DATA is set to the provided data
  • PROMPT is the text which will shown during data input

Get and Print Age Example

In this example we will simply get the input data which is age. We will print some prompt and get value and than print the provided value. Use following code.

#!/usr/bin/python3

data = input('Please enter your age:')

print('You are '+data+' years old')
Get and Print Age Example
Get and Print Age Example

Convert To Integer

We may need to convert provided value into integer. We can use int() in order to convert to integer.

#!/usr/bin/python3

data =int( input('Please enter your age:'))

print('You are '+data+' years old')

Selection Example

One of the most used situation for raw_inputor inputis selection examples. We provide some chooses and wait input according to selection. In this example we will get the age range of the user.

#!/usr/bin/python3

print('1 - Age between 0 and 18')
print('2 - Age between 19 and 35')
print('3 - Age between 35 and 60')
print('4 - Age over 60')

data = int(input('Please enter your age range'))

if(data == 1):
 print('Age is between 0 and 18')
elif(data == 2):
 print('Age is between 19 and 35')
elif(data == 3):
 print('Age is between 35 and 60')
elif(data == 4):
 print('Age is over 60')
else:
 print('Please provide acceptable value')
Selection Example
Selection Example

LEARN MORE  Linux Bash Input, Output and Redirect

2 thoughts on “How To Get Input From Keyboard with Python raw_input with Examples”

  1. sorry, but I can’t understand what could this function does?
    I use raw_input now but whatever i can’t understand what is useful when I use this function? what is the difference between this and when I use normal string

    Reply

Leave a Comment