8 Input Function
We can store the values which are provided as an input from user inside a variable.
We can implement this with the help of python built-in function input().
input() function takes input from user and always stores the provided value in the form of string.
We can use type casting after getting the input from user to convert the input data into required form.
The function accepts message parameter to inform user which value to be provided as an input.
📜 Syntax:
1 | variable_name = input("message for user")
|
Scenario 1: Get two numbers as input from the user print their addition.
💻 Example:
1 2 3 4 5 6 7 8 | num1=input("please enter 1st number:")
num2=input("please enter 2nd number:")
# Change their datatypes to int
num1=int(num1)
num2=int(num2)
print("There sum is:")
print(num1+num2)
|
✅ Output:
please enter 1st number:30
please enter 2nd number:20
There sum is:
50
We can change the datatype while accepting the input inside variable as well.
💻 Example 1:
1 2 | num1=int(input("please enter number:"))
print(type(num1))
|
✅ Output:
<class 'int'>
💻 Example 2:
1 2 | num1=input("please enter number:")
print(type(num1))
|
✅ Output:
<class 'str'>
Here are the quick notes on above topic:
Be prepared with below questions prior to your interview !
Frequently asked Interview Questions
What is input() function in Python?
How do you handle user input that requires multiple values?
What does the input function return?
Can the input function accept an optional prompt message?
How can you convert the input to a specific data type?
What happens if the user does not provide any input?
What is the default datatype of returned data by input() function?