• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

How to Get User Input in Python from Keyboard?

Aniruddha Chaudhari/66297/14
CodePython

We already know, Programming is all about processing data. To process the data program needs information as input. It can come in many ways.

Such as,

  • input from the database
  • information from external resources like machine/device/website
  • by typing on the keyboard
  • hovering or clicking by mouse

In this post, we are only interested in getting keyboard input from the user.

Here in this post, we check out, how to receive input from the keyboard.  And what is the difference between ‘raw_input()’ and input() function?

Table of Contents

  • Python 2: Getting command line input using ‘raw_input()’
  • Python 3: Keyboard input from the user using ‘input()’
  • Difference between input and raw_input function
  • How to Get User Input in Python for Both Python versions?

Python 2: Getting command line input using ‘raw_input()’

There is function raw_input(). The name itself depicts as it read raw data. It read user data as a string. It does not have the intelligence to interpret the type of data; the user has entered.

name = raw_input('Enter your keyboard input:')

All the data until you press the return key, will be read by this function.

By default, raw_input reads the input data and gives it in the form of a string.

Note: It is an in-built function, so you don’t need to import any external library.

Python 3: Keyboard input from the user using ‘input()’

It provides in build function ‘input()’ to read the input from the user.

name = input("What's your Good name? ")

Function input() reads the data from the user as a string and interprets data according to the type of data entered by the user.

If the user enters an integer/float value, Python reads it as an integer/float, unlike the raw_input() function from Python 2.

Note: You can also use input() method in Python 2. If you use the input() function in Python 2, it always read the data as a string and you have to convert it according to your need.

Let’s start exploring it further.

Difference between input and raw_input function

If you want to get input as integer or float in Python 2, you need to convert data into int or float after reading data using raw_input().

mode=int(raw_input('How old are you?:'))

As we are taking input from the user, we can not ensure if the given user input value type is a numeric data type (float or int) or not.

So it is good practice to catch the error using try and except.

try: 
  mode=int(raw_input('Keyboard Input:')) 
except ValueError:
  print("This is not a number.")

Another way is you can check the data type of the input using isdigit().

mode = raw_input('Keyboard Input:') 

if(mode.isdigit()): 
  print("Number is an integer.") 
else:
  print("Number is not an integer.")

Handling error is good practice to prevent the code from crashing at runtime.

How to Get User Input in Python for Both Python versions?

But now real confusion starts from here.

What about if you do not know the python version to whom you are going to run your code? Or do you want the code to run on both Python versions?

It’s simple. Just check the version of the python and then put the if-else statement to distinguish the Python input function as per the Python version.

Suppose if you are running code on Python 2.x, it should use the raw_input() function to read user value. If the same is going to run on Python 3.x environment, it should use the input() function.

So the first task is to find the Python version number.

To get the Python version, you need to import sys module.

Use the following code snippet to read user input for both Python versions.

from sys import version_info 

python_3 = version_info[0] 

#creates Boolean value 
#for a test that Python major version 

if python_3==3: 
  response = input("Please enter your Good Name: ") 
else:
  response = raw_input("Please enter your Good Name: ")

Conclusion:

  • Python 2.x has raw_input() function to get keyboard input. Likewise, Python 3.x has function input().
  • The input() the function has more intelligence to interpret the user input datatype than raw_input() function.
  • You can use the input() in both Python 2 and Python 3 versions.
  • The input() function in Python 2 takes every input as a string. Whereas same function in Python 3, convert the input into the appropriate data type.
  • If you want your code to work on both Python versions, use condition by checking its python version.

Hope you got the solution, how to Get User Input in Python for both Python 2 and Python 3 version. If you have any questions, feel free to ask me in a comment.

Happy Pythoning!

Python Interview Questions eBook

Python
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Comments

  • Reply
    Madhumaya
    April 10, 2019 at 11:46 pm

    Hi Aniruddha

    I had few doubts ..
    1. The example code you given in the page
    name = input(“What’s your Good name? “)
    agreed it’s asking from user. let say usser provide 12345 , then
    name = 12345
    then when i am checking the type of name .. console should return int type.. right ?

    2. what does this lines means
    from sys import version_info

    3. what value this version_info will return
    python_3 = version_info[0]

    lets assume it return 3

    then python_3 is equal to 3 .. right ?

    but in if condition we are not camparing the python_3 at all then how the if condition coming true ?

    Thanks In Advance

    • Reply
      Aniruddha Chaudhari
      April 11, 2019 at 9:23 am

      Hi Madhumaya,

      1) Every input you take from user using input() will be of string type, whether you pass ‘any string’ or ‘54545’.

      In your case ‘name’ will be a string. You have to convert it to integer. You can do this by int(name).

      2) This is the way of importing Python module/libraries. It is similar way of include header file in C/C++. In This case, we have imported version_info[] to get the Python version information. You will see “importing modules” in detail in upcoming tutorial.

      3) That was a mistake in our code. I have corrected it. Thanks 🙂

      Hope it is clear. Feel free to ask if you have any furher doubt.

  • Reply
    ASMITA
    May 15, 2019 at 1:52 pm

    the code to accept both the methods(for both python 2 and python 3) is showing indentation error in my system

    • Reply
      Aniruddha Chaudhari
      May 16, 2019 at 10:32 am

      Kindly check if you are giving a consistent number of white spaces before the start of a line in “if” and “else” block.

      If you are copy-pasting the content from this tutorial. Remove those white spaces and add again manually.

      If you still face an issue. Feel free to post the screenshot in out Python community – https://www.facebook.com/groups/cs.python/

  • Reply
    Megan Bawra
    June 16, 2019 at 8:57 pm

    How can I know which one is python 2 & python 3 versions?

    • Reply
      Aniruddha Chaudhari
      June 18, 2019 at 9:43 am

      Execute the following Python code

      from sys import version_info
      python_3 = version_info[0]

      If the value of python_3 is 3, it is Python 3. Otherwise, Python 2.

  • Reply
    Asrar Ahmed Farooqui
    May 4, 2020 at 1:05 am

    Hi Anirudha, I am a newbie and still learning the basics of programming.
    My ques is I am trying to write a simple prog that will take the input from user and compare it with some value and will reply based on that. Please check below.

    age = input("enter a number: ")
    if age == 17 or 18 or 19:
        print("you are on right path")
    elif age >= 20:
        print('You are late but still there is always hope')
    

    I want to have something like this. If the user inputted age is 17 or 18 or 19 I want to print you are on the right path and if it is more that I want to print the 2nd line. But the prob is it is always printing the 1st line.
    Can you please show where I am going wrong?

    • Reply
      Aniruddha Chaudhari
      May 4, 2020 at 9:11 am

      Hi Asrar, two changes are required here.

      1. Whenever you take user input using input(), it always takes it as a string. You have to convert it to an integer using ‘int’.
      2. Change condition in first if statement as age == 17 or age == 18 or age == 19:.

      Here is a code snippet with these two fixes.

      age = int(input("enter a number: "))
      if age == 17 or age == 18 or age == 19:
          print("you are on right path")
      elif age >= 20:
          print('You are late but still there is always hope')
      
  • Reply
    venkat
    October 8, 2020 at 7:08 pm

    Reverse each word in a sentence using python with a loop statement and check its a palindrome or not.

    • Reply
      Aniruddha Chaudhari
      October 11, 2020 at 12:15 pm

      If you are looking for the solution for your query, check these links.
      Reverse string in Python.
      Check if the string is a palindrome.

  • Reply
    Solatano Jr.
    March 14, 2021 at 9:25 pm

    Hi Anirudha,

    “Function input() reads the data from the user and interprets data according to the type of data entered by the user.”

    ^Can you clarify this further? As per taught, and as per actual coding, the ‘input( )’ function always returns string data type regardless of the input data.

    Appreciate all your hard work in putting these tutorials. I’m just worried about possible confusion.

    Warm regards,

    SJ

    • Reply
      Aniruddha Chaudhari
      March 17, 2021 at 10:29 pm

      Hi Solatano,

      We can use the input() function with both Python versions. The input() function in Python 2 takes every input as a string. Whereas the same function in Python 3, convert the input into the appropriate data type. Edited tutorial to clear this confusion.

      Thanks for bringing this topic.

  • Reply
    Kyle Sallee
    July 6, 2021 at 5:29 am
    print("This is not a number.)

    should be

    print("This is not a number.")

    And raw_input was renamed to input in Python 3.

    • Reply
      Aniruddha Chaudhari
      July 8, 2021 at 3:28 pm

      Updated. Thanks for the correction.

Leave a Reply Cancel reply

Basic Python Tutorial

  1. Python- Tutorial Overview
  2. Python- Applications
  3. Python- Setup on Linux
  4. Python- Setup on Windows
  5. Python- Basic Syntax
  6. Python- Variable Declaration
  7. Python- Numeric Data Types
  8. Python- NoneType
  9. Python- if-else/elif
  10. Python- for/while else
  11. Python- User Input
  12. Python- Multiline User Input
  13. Python- String Formatting
  14. Python- Find Substring in String
  15. Python- Bitwise Operators
  16. Python- Range Function
  17. Python- List
  18. Python- List Vs Tuple
  19. Python- Compare Two Lists
  20. Python- Sorting List
  21. Python- Delete Element from List
  22. Python- Dictionary
  23. Python- ‘is’ vs ‘==’
  24. Python- Mutable vs Immutable
  25. Python- Generator & Yield
  26. Python- Fibonacci Generator
  27. Python- Assert Statement
  28. Python- Exception Handling 
  29. Python- RegEx
  30. Python- Lambda Function
  31. Python- Installing Modules
  32. Python- Important Modules
  33. Python- Find all Installed Modules
  34. PyCharm- IDE setup
  35. Python- File Handling
  36. Python- Monkey Patching
  37. Python- Decorators
  38. Python- Instance vs Static vs Class Method
  39. Python- Name Mangling
  40. Python- Working with GUI
  41. Python- Read Data from Web URL
  42. Python- Memory Management
  43. Python- Virtual Environment
  44. Python- Calling C Function

Python Exercise

  1. Python- Tricky Questions
  2. Python- Interview Questions (60+)
  3. Python- Project Ideas (45+)
  4. Python- MCQ Test Online
  5. Python- Coding Questions (50+)
  6. Python- Competitive Coding Questions (20+)

Python String

  1. Reverse the String
  2. Permutations of String
  3. Padding Zeros to String/Number

Python List

  1. Randomly Select Item from List
  2. Find Unique Elements from List
  3. Are all Elements in List Same?

Python Dictionary

  1. Set Default Value in Dictionary
  2. Remove all 0 from a dictionary

File Handling

  1. Python- Read CSV File into List
  2. Check if the File Exist in Python
  3. Find Longest Line from File

Compilation & Byte Code

  1. Multiple Py Versions on System
  2. Convert .py file .pyc file
  3. Disassemble Python Bytecode

Algorithms

  1. Sorting- Selection Sort
  2. Sorting- Quick Sort

Other Python Articles

  1. Clear Py Interpreter Console
  2. Can I build Mobile App in Python?
  3. Extract all the Emails from File
  4. Python Shell Scripting

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard