Input

The input() Function

The input() function is used to get input from the user. When the input() function is executed, the program will wait for the user to enter some text and press the Enter key. The text entered by the user is then returned as a string.

Here's a simple example:


            name = input("Please enter your name: ")
            print("Hello, " + name + "!")
        

In this example, the input() function is used to get the user's name, which is then stored in the name variable. The print() function is then used to print a greeting to the user, using the value stored in the name variable.

Converting input to other data types

By default, the input() function returns a string. However, you can convert the input to other data types using type conversion functions like int(), float(), bool(), etc.

Here's an example of how to convert the user's input to an integer:


            age = int(input("Please enter your age: "))
            print("You will be " + str(age + 10) + " in ten years.")
        

In this example, the user's input is converted to an integer using the int() function. The program then uses this integer value to perform some calculations and print the result.

Handling user input errors

It's important to handle errors that may occur when getting input from the user. For example, if the user enters a string instead of a number, the program will throw a ValueError exception when attempting to convert the input to an integer.

To handle these errors, you can use a try/except block. Here's an example:


            try:
                age = int(input("Please enter your age: "))
                print("You will be " + str(age + 10) + " in ten years.")
            except ValueError:
                print("Please enter a valid age.")
        

In this example, the int() function is called inside a try block. If the user enters a valid integer, the program will execute the code in the try block as expected. However, if the user enters a string or some other invalid input, a ValueError exception will be raised, and the program will execute the code in the except block instead.

Conclusion

The input() statement is a powerful tool in Python that allows us to get input from users and use that input in our programs. By mastering the input() function and learning how to handle user input errors, you'll be well on your way to writing more interactive and user-friendly programs.