Python input() Function
There are many ways to take input from users such as from the keyboard, database, another computer, or mouse clicks.
In python programming, we can take the input from the user with the help of input()
function.
How does the input() function work?
When we call the input function, then the program flow stops until the user provides an input. Let’s see the basic format of the input function.
Basic format of the input() function in Python
input(message to be printed before taking the input)
It is easier to tell the user what type of input we are taking from him. So we print the message in the input function.
Example of input() function
Let’s see a simple example to take the user’s name as the input. We can do this by following two ways:
Way-1:
Here we have given the message to the user by using a separate print statement.
print("What's your name?")
user_name = input()
print(user_name)
What’s your name?
Tom
Tom
Way-2:
Here we have given the message to the user in the input function.
user_name = input("What's your name? ")
print(user_name)
What’s your name?
Tom
Specifying input type
We can easily specify the type of input from the user.
Example of taking the integer type input from the user
num_1 = int(input("enter the first number "))
num_2 = int(input("enter the second number "))
print(num_1 + num_2)
enter the first number 22
enter the second number 23
55
If we don’t try to take input then it will concatenate both the input such as
num_1 = input("enter the first number ")
num_2 = input("enter the second number ")
print(num_1 + num_2)
enter the first number 22
enter the second number 23
2223
Similarly, we can specify the input such as float and character.
Example of take the input such as float and character
name = str(input("Enter the student name "))
percentage = float(input("enter the student's percentage "))
print(name + " got ", percentage, " percent marks")
Note: If there is no type before the input function then by default string value will be returned by the input()
function.
Enter the student name rahul
enter the student’s percentage 23.2
Rahul got 23.2 percent marks
Exercises & Assignments |
---|
No Content Found. |
Interview Questions & Answers |
---|
No Content Found. |