From the previous chapters, we learned how to use string, loop, functions and methods to write a code in Python language. Now we can go one step ahead and learn how to take a input from the user.
Suppose, we are going to design an application and also want to intract with user or use in real world. Then it is must to learn how to accomplish this. This concept is very important to go further in this python tutorial, so ensure you understand every line and practice as much as possible.
What is input function?
The Input function is used to get input or data from the user via the keyboard. It stores the value provided by the user in a variable.
Syntax: input("Message")
name = input("Enter Your Name: ")
print(name) #Output: Anything you type is convert into output including number.
age = input("What is your age: ")
print(age)
print(type(age)) #Show data type
Convert Input to Interger
If you want to use the input as an integer, you can convert it using the int() function.
Your value is convert to integer.age = int(input("What is your age: ")) print(age) print(type(age)) #Show data type
How to take two input from user?
print("Add Two Numbers")
Num1 = int(input("Enter First Number: "))
Num2 = int(input(Enter Second Number: ")) print(Num1 + Num2) #print addition of give number
Taking String Input
When we want to generate output with user string input then we can create default value with print function.
name = input(Enter Your Name: ")
city = input("Enter Your City: ")
print("Hello", name)
print("You live in", city)
Convert Input to Float
If we want number in decimal then we can use Float().
price = float(input("What is the price: "))
print(price)
Create Simple Calculator with Input()
print("This is simple calculator")print("Addition", num1+num2)
num1 = int(input("Enter First Number: "))
num2 = int(input("Enter Second Number: "))
print()
print("Substraction", num1-num2)
print("Multiply", num1*num2)
print("Divide", num1/num2)
How to take multiple input in one line?
You can also take a input in one line.
a,b = int(input(Type Two numbers: ")).split()
print(a)
print(b)
Tasks
Conclusion
This is all about the input() method. Now practice this method as much as possible to stay ahead in Python. The next chapter will be "Exception Handling".
