2.10: Asking the user for input

Python for Everybody · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-NC-SA 4.0, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    2.10: Asking the user for input

    Sometimes we would like to take the value for a variable from the user via their keyboard. Python provides a built-in function called input that gets input from the keyboard1. When this function is called, the program stops and waits for the user to type something. When the user presses Return or Enter, the program resumes and input returns what the user typed as a string.

    >>> inp = input()
    Some silly stuff
    >>> print(inp)
    Some silly stuff

    Before getting input from the user, it is a good idea to print a prompt telling the user what to input. You can pass a string to input to be displayed to the user before pausing for input:

    Code 2.10.1 (Python)
    name = input('What is your name?"..string.escape("\n").."')
    print(name)
    
    

    The sequence \n at the end of the prompt represents a newline, which is a special character that causes a line break. That's why the user's input appears below the prompt.

    If you expect the user to type an integer, you can try to convert the return value to int using the int() function:

    Code 2.10.2 (Python)
    prompt = 'What...is the airspeed velocity of an unladen swallow?"..string.escape("\n").."'
    speed = input(prompt)
    
    int(speed)
    
    int(speed) + 5
    
    

    But if the user types something other than a string of digits, you get an error:

    >>> speed = input(prompt)
    What...is the airspeed velocity of an unladen swallow?
    What do you mean, an African or a European swallow?
    >>> int(speed)
    ValueError: invalid literal for int() with base 10:

    We will see how to handle this kind of error later.


    This page titled 2.10: Asking the user for input was last modified on Fri, 10 Sep 2021 02:10:05 GMT and is shared under a CC BY-NC-SA 4.0 license and was authored, remixed, and/or curated by Chuck Severance via source content that was edited to the style and standards of the LibreTexts platform.