Python tutorial-get user input


Get user input


You can allow the user to input from keyboard by using input() method.
>>> yourname=input('Enter your name:')
Enter your name:Dara
Traceback (most recent call last):
  File "<pyshell#15>", line 1, in <module>
    yourname=input('Enter your name:')
  File "<string>", line 1, in <module>
NameError: name 'Dara' is not defined
>>> 
 


You got the message as seen above. By using input() method to get input from the user, it will display the error because Python interpreter doesn’t treat the input value as a text string. Instead, it treats it as an expression. If you try to input the value with single quotes (e.g. ‘Dara’), you will succeed.
 
>>> yourname=input('Enter your name:')
Enter your name:'Dara'
>>> print yourname
Dara
>>> 
 
By asking the user to put a text string with single quotes, it is not a good practice because 100% of users do not like that. Fortunately, Python provides another method—raw_input() to allow the user to enter text strings without single quotes. By using raw_input() method, Python treats your input value as a raw string.
 
>>> yourname=raw_input('Enter your name:')
Enter your name:Dara
>>> print yourname
Dara
>>> 




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.