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

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

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.

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.

Problem Statement: Write a program to calculate the Factorial.

```#Write a python program to find the factorial of a number #Enter inputn = int(input("Enter input number: ")) # input should be an integer num = 1if 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

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:

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.

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```

Output

### How to Input Multiple Values in a Single Line

```#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

### How to Accept Multiline Input from the User

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

Output – 1

Output – 2

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.

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

Also Read: Exception Handling in Python

Also Read: Data Types in Python

1. How to Check Two String are Anagrams

```#Enter input stringsstr1 = str(input ("Enter string 1: "))str2 = str(input ("Enter string 2: ")) #Convert into lowercase and sortstr1 = sorted(str1.lower())str2 = sorted(str2.lower()) print("String 1 after sorting: ", str1)print("String 2 after sorting: ", str2) #Define a function to match stringsdef isAnagram(): if (str1 == str2) : return "The strings are anagrams." else: return "The strings are not anagrams." print(isAnagram())Copy code```

Output

Must Read: How to Check Two String are Anagrams

2. How to Check if a Python String is a Palindrome

`#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

## 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

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.