Python Input Function: A Comprehensive Guide to Getting User Input in Python

Python Input Function: A Comprehensive Guide to Getting User Input in Python

5 mins read437 Views Comment
Vikram
Vikram Singh
Assistant Manager - Content
Updated on Apr 30, 2024 09:17 IST

In the previous articles, we have seen different python functions to avoid using the same piece of code multiple times or to break multiple lines into two smaller pieces. One of the most important uses of functions is that multiple users can use them. This article will discuss another important function, i.e., python input() functions.

2023_02_MicrosoftTeams-image-171.jpg

The input function in Python is used to take input from the users, and, by default, it returns the user input in the form of a string.
Let’s take an example to get to know what we will learn in the article.

Explore How to Find an Armstrong Number Using Python

Problem Statement: Write a program to calculate the Factorial.


 
#Write a python program to find the factorial of a number
#Enter input
n = int(input("Enter input number: ")) # input should be an integer
num = 1
if n < 0:
print("Factorial does not exist for negative numbers")
elif n == 0:
print("The factorial of 0 is 1")
else:
while(n > 0):
num = num * n
n = n - 1
print("The factorial is", num)
Copy code

Output

2023_02_image-44.jpg

Now, we have to substitute the value (or the integer) to which we have to find the factorial. So, let’s find the factorial of a five.

The final output will be:

2023_02_image-54.jpg

Must Check: How to Find Factorial of a Number using Python

What is Programming What is Python
What is Data Science What is Machine Learning

So now, without further delay, let’s learn how to use Python’s input () function.

What are Input Functions in Python?

Python Input functions are built-in functions in Python that allows the programmer to accept the user’s input during the execution of the code. The input function in Python stops the execution of the program and waits for the user to provide the input, which is then assigned to a variable in the program to get the final output.

Syntax


 
input([prompt])
Copy code
  • Prompt is optional, and if it is given, it is written to standard output without a trailing new line. The function then reads a line from the input, converts it to a string, and returns it.
  •  Input function takes the prompt as an argument, displays the prompt to the users, and waits for the user to provide the input. Once the user inputs the text and presses the enter key, the function returns the string.

Let’s take some more examples to understand better. 

So, start with the basic examples first.

Example 1: Get the employee details such as name, code, and their ctc.


 
# Employee Details
# Take Input as a String
name = input("Enter The Name of Employee: ")
# Take Input as an Integer
code = int(input("Enter the Employee Code: "))
# Take Input as a Float
ctc = float(input("Enter the CTC of the Employee: "))
#print all the details:
print('\n')
print("Employee Details")
print("name", "code", "ctc")
print(name, code, ctc)
Copy code
#multiple input value in a single line
name, code, ctc = input('Enter the Employee Name, Employee Code, and CTC seprated by a space').split()
print("name", name)
print("code", code)
print("ctc", ctc)
Copy code

Output

2023_02_image-46.jpg

Also Read: Python split() function

Also Read: Keywords in Python

How to Accept Multiline Input from the User


 
# list to store multi line input
# press enter two times to exit
data = []
print("Employee Details")
while True:
line = input()
if line:
data.append(line)
else:
break
finalText = '\n'.join(data)
print("\n")
print("Final Output")
print(finalText)
Copy code

Output – 1

2023_02_image-47.jpg

Output – 2

2023_02_image-48.jpg

For the first output, we have enter only two inputs (Employee Name and Employee Code) while for the second output we have taken four inputs (Name, Age, CTC, and Department).

How to Handle User Input Error

While using the user input, it is possible to get invalid input data. So, it is essential to handle these errors.

For example, you want to take the employee code as input.


 
emp_code = int(input('Enter age: '))
Copy code

But if the user wrongly inserted the wrong value (value other than integer data type), then it will throw an error.

2023_02_image-49.jpg

Now, to handle the above error, we will use Python Try Except.

In the above example, we try to convert the input to an integer using the int() function, and if the input is not a valid integer, a value error is raised. Except block will catch up the error and prints an error message.


 
try:
emp_code = int(input('Enter Employee Code: '))
except ValueError:
print("Invalid Employee Code, Please enter a valid number.")
Copy code

Output

2023_02_image-50.jpg

Also Read: Exception Handling in Python

Also Read: Data Types in Python

Some Advanced Examples

1. How to Check Two String are Anagrams


 
#Enter input strings
str1 = str(input ("Enter string 1: "))
str2 = str(input ("Enter string 2: "))
#Convert into lowercase and sort
str1 = sorted(str1.lower())
str2 = sorted(str2.lower())
print("String 1 after sorting: ", str1)
print("String 2 after sorting: ", str2)
#Define a function to match strings
def isAnagram():
if (str1 == str2) :
return "The strings are anagrams."
else:
return "The strings are not anagrams."
print(isAnagram())
Copy code
#Enter input string
string =input("Enter string : ")
#Declare an empty string variable 
revstr =""
#Iterate string with for loop
for i in string:
    revstr = i + revstr  
print("Reversed string : ", revstr)
if(string == revstr):
   print("The string is a palindrome.")
else:
   print("The string is not a palindrome.")
Copy code

Output

2023_02_image-52.jpg

Must Read: How to Check if a Python String is a Palindrome

Conclusion

The input function in Python is a built-in function that is used to get the user input data to execute the program. In this article, we have briefly discussed how to use python input functions with the help of several examples.
Hope you will like the article.

Top Trending Article

Top Online Python Compiler | How to Check if a Python String is Palindrome | Feature Selection Technique | Conditional Statement in Python | How to Find Armstrong Number in Python | Data Types in Python | How to Find Second Occurrence of Sub-String in Python String | For Loop in Python |Prime Number | Inheritance in Python | Validating Password using Python Regex | Python List |Market Basket Analysis in Python | Python Dictionary | Python While Loop | Python Split Function | Rock Paper Scissor Game in Python | Python String | How to Generate Random Number in Python | Python Program to Check Leap Year | Slicing in Python

Interview Questions

Data Science Interview Questions | Machine Learning Interview Questions | Statistics Interview Question | Coding Interview Questions | SQL Interview Questions | SQL Query Interview Questions | Data Engineering Interview Questions | Data Structure Interview Questions | Database Interview Questions | Data Modeling Interview Questions | Deep Learning Interview Questions |

FAQs

What is the difference between input () and raw input() functions?

raw_input() function is a feature of Python 2.0, and it is not available in python 3.0. The key difference between input and raw_input is the return type of raw_input will always be a string while the return_type of input need not be string only.

How do I convert a string to an integer in Python?

In Python, the string can be converted to an integer by simply using int () keywords. Example: int (input("Enter the Employee Code").

How do I write multiple inputs in Python?

There are two methods to write multiple inputs in Python. 1. Use input() function multiple times. 2. Use split() function with input() functions.

About the Author
author-image
Vikram Singh
Assistant Manager - Content

Vikram has a Postgraduate degree in Applied Mathematics, with a keen interest in Data Science and Machine Learning. He has experience of 2+ years in content creation in Mathematics, Statistics, Data Science, and Mac... Read Full Bio