How To Get User Input In Python

When you develop a python application, you may need to get user input from the command line, this article will tell you how to get user input from the command line with an example.

1. How To Get User Input From Command Line In Python Program.

  1. You can call the python function input(prompt_message) to prompt a message to the user and get the user input as a string.
  2. Below is an example of using the input(prompt_message) function.
    user_input_str = input('Please input an integer number : ')

2. How To Use Python input(prompt_message) Function Example.

  1. This example will prompt a message to the user and let the user input an integer number.
  2. If the user input is not an integer number, then it will prompt the user to input again until you input an integer number.
  3. The python file name is GetUserInput.py.
  4. Below is the python file source code.
    # check whether the input string is an integer or not.
    def check_int(str):
        try:
            # if str is an integer then return True.
            int(str)
            return True
        except ValueError:
            # if it throws ValueError then return False.
            return False
    
    
    if __name__ == '__main__':
    
        # call the input() function to prompt the user to input an integer number. 
        user_input_str = input('Please input an integer number : ')
    
        # User input is always a string, so check whether it's value is an integer number or not.
        is_int = check_int(user_input_str)
    
        # loop to check until user input integer number value.
        while not is_int:
    
            user_input_str = input('Please input an integer number : ')
    
            is_int = check_int(user_input_str)
    
        # print out the user inputed integer value.
        print('You input an integer number, the number value is ' + user_input_str)
    
    
    
  5. When you run the above python file in the terminal, you can get the output like below.
    $ /usr/local/bin/python3 GetUserInput.py
    Please input an integer number : hello
    Please input an integer number : python
    Please input an integer number : 666
    You input an integer number, the number value is 666

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Clicky