Python raw_input Example (Input From Keyboard)

I would like to read data from the user using Python. How do I read data using raw_input()? Can you provide Python raw_input() examples?

Tutorial details
DifficultyEasy (rss)
Root privilegesNo
The raw_input() function reads a line from input (i.e. the user) and returns a string by stripping a trailing newline.
raw_input() and input() function in Python 2.x/3.x
This page shows some common and useful raw_input() examples for new users. Please note that raw_input() was renamed to input() in Python version 3.x. See below for more info.


raw_input syntax

The syntax is as follows for Python v2.x:

mydata = raw_input('Prompt :')
print (mydata)

The syntax is as follows for Python v3.x as raw_input() was renamed to input() :

mydata = input('Prompt :')
print (mydata)

In the above example, a string called mydata stores users data. Please note that if you want to compare mydata, then convert mydata to a numeric variable using int().

Python raw_input() examples

In this example, read the user name using raw_input() and display back on the screen using print():

name=raw_input('Enter your name : ')
print ("Hi %s, Let us be friends!" % name);

Sample outputs:

Enter your name : nixCraft
Hi nixCraft, Let us be friends!

In this following example, a string called choice converted to a numeric variable:

# Version 1
## Show menu ##
print (30 * '-')
print ("   M A I N - M E N U")
print (30 * '-')
print ("1. Backup")
print ("2. User management")
print ("3. Reboot the server")
print (30 * '-')
## Get input ###
choice = raw_input('Enter your choice [1-3] : ')
### Convert string to int type ##
choice = int(choice)
### Take action as per selected menu-option ###
if choice == 1:
        print ("Starting backup...")
elif choice == 2:
        print ("Starting user management...")
elif choice == 3:
        print ("Rebooting the server...")
else:    ## default ##
        print ("Invalid number. Try again...")


# Version 2
print (30 * '-')
print ("   M A I N - M E N U")
print (30 * '-')
print ("1. Backup")
print ("2. User management")
print ("3. Reboot the server")
print (30 * '-')
## Robust error handling ##
## only accept int       ##
## Wait for valid input in while...not ###
while not is_valid :
        try :
                choice = int ( raw_input('Enter your choice [1-3] : ') )
                is_valid = 1 ## set it to 1 to validate input and to terminate the while..not loop
        except ValueError, e :
                print ("'%s' is not a valid integer." % e.args[0].split(": ")[1])
### Take action as per selected menu-option ###
if choice == 1:
        print ("Starting backup...")
elif choice == 2:
        print ("Starting user management...")
elif choice == 3:
        print ("Rebooting the server...")
        print ("Invalid number. Try again...")

Sample outputs (note down invalid inputs are detected on fly):

   M A I N - M E N U
1. Backup
2. User management
3. Reboot the server
Enter your choice [1-3] : x
''x'' is not a valid integer.
Enter your choice [1-3] : 
'''' is not a valid integer.
Enter your choice [1-3] : 1
Starting backup...

Python 3 input() example

In Python version 3.x and above you need to use the input() not raw_input(). The syntax is:

mydata = input('Prompt :')
print (mydata)
Python raw_input Examples

Python 3 input() demo

🐧 Get the latest tutorials on SysAdmin, Linux/Unix, Open Source/DevOps topics:
CategoryList of Unix and Linux commands
File Managementcat
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNCentOS 8 Debian 10 Firewall Ubuntu 20.04

17 comments… add one
  • Kevin Feb 25, 2013 @ 22:34

    How to print “Hello World” in python?

    • Joshua Carr Jun 6, 2014 @ 18:40

      print(“Hello World”)

    • sivaji Jan 24, 2015 @ 11:04

      print ‘Hello World’

  • cuturrr Feb 26, 2013 @ 8:29

    nice questione

    print “Hello World”

    • Tolli Mar 5, 2013 @ 5:06

      If you are using python 3, you have to do:
      print (“Hello World!”)
      In python 3 print is a built-in function, not a keyword like in older versions.

  • Igor Oct 7, 2013 @ 11:03

    My vVersion _:D ::

    print "Welcome to Russian Roulette!!"
    number =  raw_input('Enter a number from 1 to 6 ')
    print ('you entered %s !' % number)
    q =  raw_input ('ARE you ready  ?! y or n   ' )
    if q == 'y':
        x = random.randrange(1,6)
        for i in range(20):
            print "BE READY !!"
        print ("my number is %x" % x)
        if x != int(number):
            print 'you are lucky'
            print ' BAAAAAAAAAAAAANGG !!!!!you`re dead! '
  • Nigel Haslam Sep 14, 2014 @ 4:16

    Dear nixCraft,

    Thanks for a great scripting example. I’m a novice working on a simple Turtle drawing exercise and I’ve been struggling for hours to convert some raw_input into a variable that I could pass as an argument and your code worked for me when I was about to quit.

    Encouraged by my success ( via your help) I tried to improve my implementation by adding another exception so that non valid, or out of range integers would give the user another chance to input a number. like the exception for non integers does, instead of quitting the program with an error but I’m stumped.

    I tried making a list
    myintegers = [1,2,3]

    and adding this extra code

    choice = int for int in myintegers ( raw_input(‘Enter your choice [1-3] : ‘) )

    but I found that lists are made up of strings, not integers :(

    So I tried to cast my list of strings into a new list of integers :

    new_integers = [];
    for n in myintegers:

    and tried
    choice = int for int in new_integers ( raw_input(‘Enter your choice [1-3] : ‘) )

    I suspect that it’s my way of checking if the integer is in the list that’s falling down.

    Any pointers?

    Thanks for sharing.

    • Robb Tolliver Sep 22, 2014 @ 3:41

      How about this?

      valid_choices = [1,2,3]
      choice = None
      while choice not in valid_choices:
      choice = int(raw_input(‘Enter your choice [1-3] : ‘))

  • athinak Feb 15, 2016 @ 8:35

    Submit only your code, not the output, but make sure that you run the program and it gives the the desired output before submitting.

    # 2.1 Write a program to prompt the user for his or her name using raw_input. Also, prompt the hours and rate per hour using raw_input to compute gross pay. Use 35 hours and a rate of 2.75 per hour to test the program (the pay should be 96.25). You should use raw_input to read a string and float() to convert the string to a number. Finally print a statement so that it looks like the one below.

    # The output should look like the following but with your name instead of mine:

    Enter Name: Karolos

    Enter Hours: 35

    Enter Rate: 2.75

    The total Pay for Karolos is $ 96.25

    plzzzz help me !
    how do i do that?

  • Cinco Jun 16, 2016 @ 7:37

    Why I can’t use raw_input in my Python 3.5.1 shell?

    name=raw_input('Enter your name : ')
    Traceback (most recent call last):
      File "", line 1, in 
        name=raw_input('Enter your name : ')
    NameError: name 'raw_input' is not defined
    • Nicholas M Carr Dec 18, 2016 @ 1:42

      They changed raw_input() to just input()

      So your script would be:

      name = input(‘Enter your name : ‘)

    • Nicholas M Carr Dec 18, 2016 @ 1:43

      You have to change raw_input() to input()

      So your script would be:

      name = input(‘Enter your name : ‘)

    • Ny4N Dec 18, 2016 @ 4:01

      I want to know too

      • 🐧 Vivek Gite Dec 18, 2016 @ 8:45

        raw_input() was renamed to input(). So code must be:

        name=input('Enter your name : ')
  • rajib Jun 21, 2016 @ 17:47

    how can i detect a start flag character of a string to process the next
    ST234 P342…plz hlp

  • Benjamin Obiagba Jul 2, 2016 @ 21:05

    Thanks for this great example, really made me more enlightened.

  • Aaryan Feb 1, 2017 @ 3:40

    python is so hard

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.