Input In Python (Full Guide With Examples)

In this tutorial, we will learn about how to take input in python. We will also discuss some practical examples. Let’s start with the definition.

Definition :

Input in python is the builtin function and used to take text inputs from the user. it also accepts an optional string argument.

Syntax :

input([prompt])

Input In Python Examples

For a better understanding of input function in python let’s look at some examples.

Example 1 : Ask User Name

In this example, we are using the input function to ask the user’s name and greet the user.

name = input("Enter your Name : ")
print("Hello!",name)

Save and run the above code you should see the following output.

Output :

input in python code example 1 output

Example 2 : Accept Integer Input

number = int(input("Enter Any Number : "))
print("You have entered ",number)

we used the builtin int() function to convert the string from input function to integer.

You can similarly use the builtin float() function to accept a floating-point number from the user.

Example 3 : Create An Calculator Using Input

Let’s use the input function to create an simple console based calculator.

number1 = float(input("Enter the Number 1 : "))
number2 = float(input("Enter the Number 2 : "))

operation = input("Enter the operation (+,-,*,/) : ")

if operation == '+':
    print(number1 + number2)
elif operation == '-':
    print(number1-number2)
elif operation == '*':
    print(number1*number2)
elif operation == '/':
    print(number1/number2)
else:
    print("Invalid Operation!")

Here is the output of above code.

Output :

Enter the Number 1 : 5
Enter the Number 2 : 5
Enter the operation (+,-,*,/) : +
10.0

If you are a beginner in python below is the code explanation of the above example.

  • We first take two numbers from the user and convert them into float using float() builtin function.
  • We then ask the user about what mathematical operation to perform.
  • We then create an if-elif-else block and checks for operation and operate accordingly.

Input For Python2.x Users

Note : python2.x does not have input() function . instead, you have to use raw_input() function. here is the example for that.

name = raw_input("Enter Your Name : ")
print("You have Entered : ",name)

Another Way Of Taking User Inputs (Optional)

Note : This section is completely optional.

You might be wondering. but here is another way of taking user inputs in python.

import sys

print("Enter Your Name : ",end = '')
name = sys.stdin.readline()
print(name)
  • We first import the builtin sys module.
  • Then we used print() function to print an input message on the console.
  • Then we used sys.stdin,readline() function to take user input.
  • Then we simply printed the output on the console.

That’s the wrap for this tutorial.

Also learn about builtin all() and any() functions.

This Post Has 2 Comments

Leave a Reply