Pythondex
Learn Python

Take Input In Python

Taking input from users is a crucial aspect of programming, facilitating dynamic interactions within a program so let’s see how to take a input from the user in python programming.

Syntax


input("Message to display")

In Python, you can interact with users by taking input from them. To take input in python you can use the builtin input() function. In the function we can pass a message that will display to the user, providing clarity about the expected input.

Example


name = input("What is your name: ")

print(name)

In the above example, we used the input() function to prompt the user with the question “What is your name: ” The program pauses, awaiting user input. Once you provide an input, the program stores it in the ‘name’ variable and then prints the entered text.

Convert Input to Other Data Types

Suppose you want to take a integer as input from the user using the input function, keep in mind that the input is initially treated as a string. Consider the following example:


age= input("What is your age: ")

print(type(age))

If you run the above program it will prompt you “what is your age” if you enter a integer say 19 it will print the type of age variable <class ‘str’> which means a string but we wanted a integer.

So whenever you want to take integer as input first you need to convert it so let’s see how to do it.

Take Integer Input


age = int(input("What is your age: "))

print(type(age))

To transform a string into an integer, you can use the built-in int() function. When converting string input to an integer, simply enclose the int() function around the input() function, as shown in the above example.

Take Float Input


grade = float(input("What is your grade: "))

print(type(grade))

To convert string input to float type again in python you can use a built-in function float(). You need to enclose the float() function around the input() function, as shown in the above example.

To conclude use input() funtion directly to take string input and enclose int() or float() function in input() function to take number input.

So this was everything you needed to know about taking inputs in python.