input() Function in Python

Introduction

Hope you've learned how to print anything in python. The next important task is to take input from the users. In python, we use the input() function to give inputs to a program. It's a built-in function. By default, it takes string values. Let's see an example.


name=input("Enter your name: ")
print(type(name))
print("Your name is "+ name)

Output

Enter your name: Alex
<class 'str'>
Your name is Alex

Typecasting Input

As you've seen above, the input() function takes string values by default. If you want to take inputs as integers, float, or whatever, you must perform typecast in that format. Don't worry, it's so simple. The below example is for you.


num_1 = input("Enter a number: ")
print("Before Typecasting: ", type(num_1))
# Type Conversion
num_2 = int(input("Enter a number: "))
print("After Typecasting: ", type(num_2))

Output

Enter a number: 55
Before Typecasting:  <class 'str'>
Enter a number: 88
After Typecasting:  <class 'int'>

More than One Input at a Line

In python, you can take multiple inputs from the users in a single line. To do so you have to use the split() method to tell the program which delimiter you want to use to separate two values from each other. For example, if you pass a comma(,) to the split function, you have to enter input values separate by a comma.

In the below example, we will take Name and Age of a person together at once. So we declared two different variables 'name' and 'age' in a single line and used the split() function to separate those two values by a comma (delimiter).


# Two inputs at a line
# Split function
name, age = input("Enter Name & Age separated by a comma: ").split(",")
print(f"Name is: {name} & Age is: {age}")

Output

Enter Name & Age separated by a comma: Alex,24
Name is: Alex & Age is: 24

Subhankar Rakshit

Meet Subhankar Rakshit, a Computer Science postgraduate (M.Sc.) and the creator of PySeek. Subhankar is a programmer, specializes in Python language. With a several years of experience under his belt, he has developed a deep understanding of software development. He enjoys writing blogs on various topics related to Computer Science, Python Programming, and Software Development.

Post a Comment (0)
Previous Post Next Post