In this Python tutorial, we will learn how to accept user input in Python. Python has a rich set of built-in functions, in this tutorial we will discuss one of them, input() function for input operation.
Python Input Function
Python 3 has a built-in function input(), to accept keyboard input. The input() method reads a line from the console and converts it into a string. The input() method takes a single optional parameter.
Syntax:
input([prompt])
prompt (Optional): A text message for the user, that is written on the screen for user instruction.
Keyboard Input in Python
Accept a Text (String) Input in Python
name=input("Enter Your Name")
print(name)
#to check type of input in python
print(type(name))
Example: Input in python is always String.
a=input("Enter First Number: ")
b=input("Enter Second Number: ")
c=a+b
print(c)
Enter First Number: 11
Enter Second Number: 22
1122
Note: In the above python input example result is 1122 because, Plus (+) symbol concatenate the value of two variables. input() method accept value as a string, even if you have enter a number.
Accept an Integer Input in Python
a=int(input("Enter First Number: "))
b=int(input("Enter Second Number: "))
c=a+b
print(c)
int() – The int() function in Python, converts the given value in Integer. In the above example input() accept the value as a string, after that int() method converts the input in integer, so we can perform the mathematical operation.
Accept a Float Input in Python
a=float(input("Enter First Number: "))
b=float(input("Enter Second Number: "))
c=a+b
print(c)
float() – The float() function in Python used to convert the string in floating number. The function accepts a string value as an argument and returns float.