Input
Accepting Input from the User
Accepting input from the user is a common operation in programming. Any piece of software needs a functional interface to interact with the user. For example, on apps like Facebook, Instagram, and Twitter, the text entered in comment boxes is considered input. This input is processed by code in the backend and displayed as a comment.
Python provides a built-in function input() to accept input from the user. It’s simple yet powerful:
In this case, the interpreter waits for you to enter text. Once you press enter, the input is stored in the variable x. The output looks like this:
You can also prompt the user to enter a specific type of input by passing a string argument to the input() function:
Now, let’s examine the type of the variable x:
No matter what you enter (integer, float, string, or boolean), the input() function always returns a string. If the user enters 123, it's processed as the string '123'.
Type Conversion
If you want to convert a string into an integer, Python provides the built-in function int():
This process is called type conversion. You can also convert an integer to a string using the str() function:
To accept an integer input from the user, you can convert the string returned by input() into an integer:
You can also combine the two operations in one line:
In this case, the output of the input() function is passed as an argument to int(). Be careful, though! If the user enters a float value, the following code will raise a ValueError:
Built-in Functions
We’ve been using the term built-in functions often. These are predefined functions in Python that accept inputs and produce outputs. For example, print() is a built-in function that accepts input and prints it to the console. Here are a few more useful built-in functions:
round(): Accepts a number and returns the closest integer. Example:round(1.2)returns1, whileround(1.9)returns2.abs(): Accepts a number and returns its absolute value. Example:abs(-1.2)returns1.2.int(): Converts a string representing an integer into anint. Example:int('123')returns123. If a float is passed, the decimal part is discarded. Example:int(1.2)returns1, andint(-2.5)returns-2.pow(): Accepts two arguments and returns the value ofx ** y. Example:pow(2, 3)returns8. It also supports a third argument:pow(x, y, z)returns(x ** y) % z.isinstance(): Used to check if an object is of a specific type. Example:isinstance(3, int)returnsTrue, andisinstance('hello', str)also returnsTrue.
The Python documentation provides a complete list of built-in functions for more reference.