HOW TO GETTING INPUT FROM THE USER IN PYTHON PROGRAMMING

GETTING INPUT FROM THE USER

The built­in input function requests and obtains user input:

In [1]: name = input("What's your name? ")
What's your name? Paul

In [2]: name
Out[2]: 'Paul'

In [3]: print(name)
Paul

The snippet executes as follows:

  • First, input displays its string argument—a prompt—to tell the user what to type and waits for the user to respond. We typed Paul and pressed Enter. We use bold text to distinguish the user’s input from the prompt text that input displays.
  • Function input then returns those characters as a string that the program can use. Here we assigned that string to the variable name.

Snippet [2] shows name’s value. Evaluating name displays its value in single quotes as 'Paul' because it’s a string. Printing name (in snippet [3]) displays the string without the quotes. If you enter quotes, they’re part of the string, as in:

In [4]: name = input("What's your name? ")
What's your name? 'Paul'

In [5]: name
Out[5]: "'Paul'"

In [6]: print(name)
'Paul'

Function input Always Returns a String

Consider the following snippets that attempt to read two numbers and add them:

In [7]: value1 = input('Enter first number: ')
Enter first number: 7
In [8]: value2 = input('Enter second number: ')
Enter second number: 3
In [9]: value1 + value2
Out[9]: '73'

Rather than adding the integers 7 and 3 to produce 10, Python “adds” the string values '7' and '3', producing the string '73'. This is known as string concatenation. It creates a new string containing the left operand’s value followed by the right operand’s value.

Getting an Integer from the User

If you need an integer, convert the string to an integer using the built-­in int function:

In [10]: value = input('Enter an integer: ')
Enter an integer: 7
In [11]: value = int(value)
In [12]: value
Out[12]: 7

We could have combined the code in snippets [10] and [11]:

In [13]: another_value = int(input('Enter another integer: '))
Enter another integer: 13

In [14]: another_value
Out[14]: 13

Variables value and another_value now contain integers. Adding them produces an integer result (rather than concatenating them):

In [15]: value + another_value
Out[15]: 20

If the string passed to int cannot be converted to an integer, a ValueError occurs:

In [16]: bad_value = int(input('Enter another integer: '))
Enter another integer: hello
---------------------------------------------------------------ValueError           Traceback (most recent call last)<ipython­-input­-16­cd36e6cf8911> in <module>()
-----> 1 bad_value = int(input('Enter another integer: '))
ValueError: invalid literal for int() with base 10: 'hello'

Function int also can convert a floating­point value to an integer:

In [17]: int(10.5)
Out[17]: 10

To convert strings to floating­point numbers, use the built-­in float function.

*

Post a Comment (0)
Previous Post Next Post