2.6 Getting Input from the User

  • Built-in input function requests and obtains user input.
In [1]:
name = input("What's your name? ")
In [2]:
name
Out[2]:
'Paul'
In [3]:
print(name)
Paul
  • If you enter quotes, they’re input as part of the string.
In [4]:
name = input("What's your name? ")
In [5]:
name
Out[5]:
'"Paul"'
In [6]:
print(name)
"Paul"

Function input Always Returns a String

In [7]:
value1 = input('Enter first number: ')
In [8]:
value2 = input('Enter second number: ')
In [9]:
value1 + value2
Out[9]:
'73'
  • Python “adds” the string values '7' and '3', producing the string '73'.
  • Known as string concatenation.

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: ')
In [11]:
value = int(value)
In [12]:
value
Out[12]:
7
  • Can combine int and input in one statement.
In [13]:
another_value = int(input('Enter another integer: '))
In [14]:
another_value
Out[14]:
3
In [15]:
value + another_value
Out[15]:
10
  • If the string passed to int cannot be converted to an integer, a ValueError occurs.
In [16]:
bad_value = int(input('Enter another integer: '))
------------------------------------------------------------------------
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

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 2 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.