For enquiries call:

Phone

+1-469-442-0620

HomeBlogProgrammingUser Input in Python with Examples [A Complete Guide]

User Input in Python with Examples [A Complete Guide]

Published
25th Jan, 2024
Views
view count loader
Read it in
7 Mins
In this article
    User Input in Python with Examples [A Complete Guide]

    In Python programming, interacting with users is a key part of collecting data and showcasing results. Here, we'll explore the ins and outs of user input, a vital aspect for developers. Python offers integrated features like the input() method in the latest version and raw_input() in earlier ones. If you're looking to enhance your Python programming skills, understanding user input is essential, and this knowledge can be gained through Python Programming training. I'll guide you through the syntax, examples, and practical uses of these functions, highlighting how they help developers effortlessly communicate with users. Together, we'll unravel the simplicity and effectiveness of Python user input, empowering you to enhance the interactivity of your Python applications. Let's dive into the world of Python user input! 

    As developers, we need to communicate with users to collect data or to generate results. Many applications today use different ways to request a certain form of input from the user. Python offers us integrated features to take the input. The latest version of Python uses the input() method while the earlier version uses the raw_input() method.

    To do this, whave to click the Enter button after entering the value from the keyboard. The input() function then reads the user’s value. The input function reads a line from the console, then converts it to a string, and returns it. To read about Self in Python, click here!

    What are User Inputs in Python? 

    In Python programming, understanding user input is fundamental for developers aiming to create interactive applications. Here's a breakdown of what user inputs entail: 

    1. Purpose: User inputs allow developers to collect data or obtain specific information from users, fostering interaction and customization within Python applications. 
    2. Input Methods: Python provides integrated features for capturing user inputs. The input() method, predominant in the latest Python version, and the older raw_input() method serve as mechanisms to gather information. 
    3. Syntax: The syntax of the input() function is straightforward – input(prompt). The prompt string guides users, indicating the type of input expected and enhancing the user experience. 
    4. Data Conversion: The input() function treats all input as strings. To work with numerical values, developers can use conversion functions like int() or float() to ensure the correct data type. 
    5. Handling Different Data Types: Python user input covers a spectrum of data types. Whether capturing strings, integers, or floats, developers can tailor their approach based on the specific requirements of the application. 
    6. Error Handling: Python addresses potential errors, such as EOFError, that may occur during the input process. Handling these exceptions ensures a smooth user experience and prevents unexpected disruptions. 
    7. Applications: User inputs play a crucial role in a variety of applications, from simple data entry tasks to more complex scenarios like decision-making based on user choices. 

    By comprehending user inputs in Python, developers gain the ability to create applications that are not only functional but also user-friendly and adaptable to diverse input scenarios. This understanding forms the basis for building dynamic and engaging Python programs that cater to the unique needs of individual users.

    Syntax of input() Function

    The syntax of input() function is: 

    input(prompt) 

    In the console, the prompt string is printed, and the user is given the command to enter the value. You should print some useful information to help the user enter the expected value. 

    Getting User Input in Python

    The input() function receives the user input from the keyboard and stores it into a variable name. Herestris a variable and the print() function prints it to the screen. 

    Getting User Input in Python

    The input() function delays the execution of a program to allow the user to type the input from the keyboard. On pressing Enter, all characters are reads and returned as a string.

    String input from the user:

    Example:

    Here is an example of getting the user input and printing it on the console. 

    str = input(“Enter your name: “) 
    print(str) 

    Output: 

    Enter your name: Joseph 
    Joseph 

    Float Input from user:

    We will use float() function to convert the received input into a float value. 

    Example:

    value = float(input("Enter a value: ")) 
    print(value) 

    Output: 

    Enter a value: 200.99 
    200.99 

    How to Get an Integer as the User Input?

    The input function converts whatever you enter as an input into a string. If you enter an integer value, the input() function will convert it to a string. 

    To use the integers, we can use the built-in functions to convert it into an int. 

    Example: 

    value =input("Enter an integer:\n") 
    value =int(value) 
    print(f'The entered number is {value} and its square is {value ** 2}') 

    Output: 

    Enter an integer: 
    10 
    The entered number is 10 and its square is 100 

    Example: 

    # take multiple inputs in array  
    input_str_array = input().split()  
    print("array:", input_str_array)  
    # take multiple inputs in array  
    input_int_array = [ int(x) for x in input().split()]  
    print("array:", input_int_array) 

    Output: 

    10 20 30 40 50 60 70 
    array: ['10', '20', '30', '40', '50', '60', '70'] 
    10 20 30 40 50 60 70 
    array: [10, 20, 30, 40, 50, 60, 70]

    Integer as the User Input example

    Python user input and EOFError Example: 

    EOFError in Python is one of the exceptions to handlerrors and is raised in scenarios such as the interruption of the input() function in both Python version 2.7 and Python version 3.6, as well as other versions after version 3.6 or when the input() function reaches the unexpected end of the file in python version 2.7, i.e. the functions do not read any data before the end of the input is encountered.  

    Methods such as read() must return a string that is empty at the end of the file, which is inherited in Python from the exception class that is inherited in Base Exception class. This mistake often happens with online IDEs. 

    If theinput()function did not read any data then the Python code will throw an exception i.e. EOFError. 

    value =input("Please enter an integer:\n") 
    print(f'You entered {value}') 

    Output: 

    Enter a value: Traceback (most recent call last): 
    File “example.py”, line 1, in <module> 
    value = input(“Please enter an integer: “) 
    EOFError 

    Working of EOFError in Python

    1. The BaseException class inherits the EOFError class as the base class of the Exception class. 
    2. EOFError technically is not an error, but an exception. When the built-in functions, such as the input() function or read() function return a string that is empty without reading any data, the EOFError exception is raised. 
    3. This exception is raised if our software tries to retrieve anything and make changes to it, but if no data is read and a string is returned, the EOFError exception is raised. 

    Steps to Avoid EOFError in Python

    If End of file Error or EOFError occurs, the exception EOFError is raised without reading any information by the input() function. We should try to enter something like CTRL + Z or CTRL + D before submitting the End-of-file exception to prevent the raising of this exception. 

    Example: 

    try: 
    data = raw_input ("Do you want to continue?: ") 
    except EOFError: 
    print ("Error: No input or End Of File is reached!") 
    data = "" 
    print data 

    Output: 

    The input provided by the user is being read which is: Hello this is demonstration of EOFError Exception in Python. 
    The input provided by the user is being read which is: EOF when reading a line. 

    Explanation: In the above program, try to prevent the EOFError exception with an empty string, which doesn't print the error message of the End Of File and rather prints the personalized message that is shown in the programand prints the same on the output.

    You can use the try and catch block if the exception EOFError is processed. 

    Python User Input Choice Example

    Python provides a multiple-choice input system. You have to first get the keyboard input by calling theinput()function. Then evaluate the choice by using the if-elif-else structure. 

    value1 =input("Please enter first integer:\n") 
    value2 =input("Please enter second integer:\n") 
    v1 =int(value1) 
    v2 =int(value2) 
    choice =input("Enter 1 for addition.\nEnter 2 for subtraction.\nEnter 3 for Multiplication:\n") 
    choice =int(choice) 
    ifchoice ==1: 
    print(f'You entered {v1} and {v2} and their addition is {v1 + v2}') 
    elifchoice ==2: 
    print(f'You entered {v1} and {v2} and their subtraction is {v1 - v2}') 
    elifchoice ==3: 
    print(f'You entered {v1} and {v2} and their multiplication is {v1 * v2}') 
    else: 
    print("Wrong Choice, terminating the program.") 
    
    

    Output: 

    Please enter first integer: 
    20 
    Please enter second integer: 
    10 
    Enter 1 for addition. 
    Enter 2 for subtraction. 
    Enter 3 for Multiplication: 
    2 
    You entered 20 and 10 and their subtraction is 10

     User Input Choice Example

    Python raw_input() function

    Python raw_input function is a built-in function used to get the values from the user. This function is used only in the older versions of Python i.e. Python 2.x version.  

    • Two functions are available in Python 2.x to take the user value. The first is the input function and the second is the raw_input() function.  
    • The raw_input function in Python 2.x is recommended for developers. This is because the input function is vulnerable in version 2.x of Python.

    Top Cities Where Knowledgehut Conducts Python Certification Courses Online

    Python Course in BangalorePython Course in ChennaiPython Course in Singapore
    Python Course in DelhiPython Course in DubaiPython Course in Indore
    Python Course in PunePython Course in BerlinPython Course in Trivandrum
    Python Course in NashikPython Course in MumbaiPython Certification in Melbourne
    Python Course in HyderabadPython Course in KolkataPython Course in Noida

    Python 2.x environment setup: 

    Python 2 must be installed in your system in order to use the raw input()function. Use python2 instead of python or Python3 if you run your programfrom a terminal. Therefore, the execution sample command is: 

    $python2 example.py 

    It depends on how your python haveinstalled. In conclusion, you must run your Python program using the version python 2.x if you use the raw_input function. 

    You can modify your Python compiler if you use PyCharm IDE. Go to File -> Configuration -> Project -> Project Interpreter for that purpose. Then selectPython 2.x from the list.

    Example 1: 

    We will see a code written in Python 2.x version. 

    name = raw_input(‘Enter your name : ‘) 
    print ‘Username : ‘, name 

    Output: 

    Enter your name : Steve 
    Username : Steve 

    Example 2: 

    # input() function in Python2.x  
    value1 = raw_input("Enter the name: ")  
    print(type(value1))  
    print(value1)  
    value2 = raw_input("Enter the number: ")  
    print(type(value2))  
    value2 = int(value2)  
    print(type(value2))  
    print(value2)

    Output: 

    Enter the name: Jenny
    <type ‘str’> 
    Jenny 
    Enter the number: ‘9876’ 
    <type ‘str’> 
    <type ‘int’> 
    9876

    The "Jenny" value is taken from the user in the value1variable here and stored in the value1. The string for raw input function is always the type of value stored. The value “9876” is takenfrom the user and storedin the variable value2. The variable value2 type is a string now and the type needs to be converted to an integer with int(). The value2 variable saves an integer type for the value "9876." 

    The function raw input() was deactivated and removed from Python 3. You can update now if you're still on a Python 2.x. 

    Conclusion

    In Python, I rely on a basic framework for Python user input. The input function serves as my go-to tool, reading and transforming a line from the console into a string. It automatically converts all input into a string format, and when I need to adjust the format, I simply use a conversion type. 

    Its primary purpose in my programming endeavors is to offer users options and dynamically alter the program flow based on their input. I've noticed that the software patiently awaits the user's input indefinitely, which is great, but having a timeout and default value would be handy if users take their time. 

    I've come across EOFError, which is technically not an error but an exception, especially important to understand during Python Programming training. This occurs when functions like input() or read() return an open string without reading any data, triggering the EOFError exception. It's a nuanced aspect of user input handling that I've encountered in my Python programming experiences. 

    Profile

    Ramulu Enugurthi

    Blog Author

    Ramulu Enugurthi, a distinguished computer science expert with an M.Tech from IIT Madras, brings over 15 years of software development excellence. Their versatile career spans gaming, fintech, e-commerce, fashion commerce, mobility, and edtech, showcasing adaptability in multifaceted domains. Proficient in building distributed and microservices architectures, Ramulu is renowned for tackling modern tech challenges innovatively. Beyond technical prowess, he is a mentor, sharing invaluable insights with the next generation of developers. Ramulu's journey of growth, innovation, and unwavering commitment to excellence continues to inspire aspiring technologists.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Programming Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon