Python3/2 differences - input() vs raw_input() - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: General (https://python-forum.io/forum-1.html) +--- Forum: Tutorials (https://python-forum.io/forum-4.html) +---- Forum: Python Installation and Execution (https://python-forum.io/forum-41.html) +---- Thread: Python3/2 differences - input() vs raw_input() (/thread-11439.html) |
Python3/2 differences - input() vs raw_input() - buran - Jul-09-2018 One of the differences between Python3 and Python2 is related to taking input from the user. It's also one of the common gotchas that newbies face when try to run Python3 code with Python2 interpreter. Long story short Following table summarize the difference: Python2In Python2 there are raw_input() and input() .
Using input() in Python2 code is generally discouraged and considered security risk as user can pass as input malicious code that will yield unexpected and/or dangerous results (e.g. they can enter something like __import__('os').remove('important_file') ). Yet often newbies are tempted to use input() when they want to take a numeric input and they don't know how to convert from str to int /float .Python3 In Python3 there is no raw_input() , just input() . That is raw_input() from Python2 being renamed input() . So in Python3 input() returns str .>>> user_input = input('Enter something: ') Enter something: 1 >>> user_input '1' >>> type(user_input) <class 'str'> >>> user_input = input('Enter something: ') Enter something: range(3) >>> user_input 'range(3)' >>> type(user_input) <class 'str'>If you want to mimic Python2 input() you need to use eval(input()) . Same warning apply as with input() in Python2 code.>>> user_input = eval(input('Enter something: ')) Enter something: range(3) >>> user_input range(0, 3) >>> type(user_input) <class 'range'> >>> user_input = eval(input('Enter something: ')) Enter something: list(range(3)) >>> user_input [0, 1, 2] >>> type(user_input) <class 'list'>Use Python3 Warning If you a newbie, being directed here as an answer to your question, then probably you use Python2. Given that official support for Python2 will end January 1st, 2020 you should start by learning Python3, not Python2. Python3 has been around for quite some time and there is no reason why you should start with/stick to Python2. If are using outdated learning materials (textbook, online course, etc.) that reference Python2, you should find more current one, install latest Python3 for your OS and switch to learning Python3. |