What is input in Python?

Amit Dhanwani on October 18, 2022

Input in Python : An introduction

Python programming has earned a reputation as an all-rounder. No other programming language comes close to Python’s level of acceptance among developers.

There are several built-in functions in Python that are used to carry out particular tasks.

In a programming framework, a built-in function is already specified with a collection of statements that carry out a certain function. As a consequence, users may utilize this function immediately in their program or application without having to write it themselves.

Each programming framework has a unique set of capabilities and offers a variety of built-in features that differ from one to another.

To collect information or provide results, developers need to communicate with individuals. Today, many apps employ various techniques to ask the user for a certain type of data.

Python has built-in capabilities for taking input. The raw_input() method is used by Python’s older versions, whereas the input() method is used by Python’s most recent version.

For interactive applications to be built, user input is essential. Each computer language’s implementation of an input interface is distinct.

C++ has scanf, Java has the Scanner class, and Ruby has gets.

While keyboard input is the most common source of this input, it can also come from other sources such as mouse clicks, trackpad movements, sensors, etc.

As usual, Python’s input() method offers a straightforward structure for gathering user input.

The input function takes a line from the console, transforms it into a string, and then outputs the string.

 

Input

 

In order to store the input in our code, we will need a variable. A data container is a variable.

 

Example:

codingal = “Love”

Here, codingal is the variable name that has Love as a value.

The variable’s value was predefined in the code above. We might want to include user inputs to offer additional flexibility.

At some point in the code, a developer could frequently want to request user input. Python has the input() method to do this.

In Python Command Line apps, the input() method is used to collect data from the user.

There are several methods for inputting information. The fundamental Python input operations are listed below:

Use input() to communicate with a program that is currently executing.

You can ask a question, obtain an answer, and provide a prompt so that the user knows what to type.

The Basic syntax of the input() function is:

input(prompt)

Where prompt is a message that will be shown to the user on the screen when input is requested; this string should provide a hint of the usage and kind of data you are expecting, and return is the value that the function returned.

For example, “Enter Name:”

The program execution stops when the input() function is called until the user provides some input. After adding further data, the user clicks the Enter key. The inputted string is returned to the application via the input function.

Example:

name=input("What your’s name?\n")
print(type(name))

What your’s name?

Codingal

<class 'str'>

 

By default, Python accepts every input as a string input. We must explicitly transform the input in order to convert it to any other data type.

For instance, we must use the int() and float() methods, respectively, to convert the input to an int or a float.

 

Accept the user’s input as an integer

 

For accepting numbers, we must perform some explicit type conversion as the input() method returns everything as a string.

The int() method will be used in this case.

Syntax:

var_name  = int(input(prompt))

Example:

number = int(input(“Enter a number: “))

The function int(string) transforms a string to an integer type.

 

A program to print the sum of two numbers taken from the user:

num1 = int(input("Enter first num: "))
num2 = int(input("Enter second num: "))
print('Type of num_1:',type(num1))
print('Type of num_2:',type(num2))
result = num1 + num2
print("The sum of given numbers is: ", result)

Enter first num: 2

Enter second num: 3

Type of num_1: <class 'int'>

Type of num_2: <class 'int'>

The sum of given numbers is:  5

 

Accept the user’s input as an float:

 

For accepting floating numbers, we must perform some explicit type conversion as the input() method returns everything as a string.

The float() method will be used in this case.

Syntax:

var_name  = float(input(prompt))

Example:

number = float(input(“Enter a number: “))

The function float(string) transforms a string into a float type.

A program to double the floating number taken from the user:

number = float(input("Enter value: "))
print('Type of number:',type(number))
answer = number*2
print("Double of the given numbers is: ", answer)

Enter value: 8.6

Type of number: <class 'float'>

Double of the given numbers is:  17.2

 

Note: The incorrect type of data value like a string, it will result in an error message being shown.

Example:

Consider the same program to double the floating number taken from the user:

number = float(input("Enter value: "))
print('Type of number:',type(number))
answer = number*2
print("Double of the given numbers is: ", answer)

Enter value: codingal

Traceback (most recent call last):

File "main.py", line 1, in <module>

number = float(input("Enter value: "))

ValueError: could not convert string to float: 'codingal'

 

Accept the user’s multiple inputs in Python

 

Python’s input() function allows us to provide multiple inputs of the same data type at once.

For example:

let’s ask the user for some information about an employee and save it in several variables.

name, age, city = input("Enter the employee's name, age, and city separated by space:\n").split()
print("Employee Name:", name)
print("Employee Age:", age)
print("Employee City:", city)

Enter the employee's name, age, and city separated by space:

Codingal 34 Bangalore

Employee Name: Codingal

Employee Age: 34

Employee City: Bangalore

 

To avoid getting the following error, you must only press enter after writing all of the variable input values, separated by spaces.

name, age, city = input("Enter the employee's name, age, and city separated by space:\n").split()
print("Employee Name:", name)
print("Employee Age:", age)
print("Employee City:", city)

Enter the employee's name, age, and city separated by space:

codingal

Traceback (most recent call last):

File "main.py", line 1, in <module>

name, age, city = input("Enter employee's name, age and city separated by space:\n").split()

ValueError: not enough values to unpack (expected 3, got 1)

However, what happens if you are unaware of the number of input values?

Consider the scenario where you must input a list of numbers and have their total returned. You are unaware of how many items there are on that list. How should this list be entered?

For this issue, both the divide and the map functions are employed. The entered string will be split into a list of strings using the split() function. The map() method will then execute the int operation on each element of the list.

Example:

input_list = input("Enter a list of numbers separated by space:\n ").split()
print('List: ',input_list)
number_list = list(map(int,input_list))
print('Number List: ',number_list)
print('List sum:', sum(number_list))

Enter a list of numbers separated by space:

1 2 3 4 5 6 7 8 9

List:  ['1', '2', '3', '4', '5', '6', '7', '8', '9']

Number List:  [1, 2, 3, 4, 5, 6, 7, 8, 9]

List sum: 45

In the example above:

  • Numbers are separated from one another by spaces in the string that input() produces.
  • A list of texts divided on spaces is the output of the split() function.
  • The function map() creates a map object by performing the int() operation on each element of the list.
  • The map object is converted back into a list via the list() method.

Inputs for the Sequence Data Types like List, Set, Tuple, etc.

For List and Set, there are two different methods by which the user’s input can be collected.

  1. Taking List/Set elements one by one by using the append()/add() methods.
  2. Using map() and list() / set()  methods.

 

Taking list/set elements one by one

 

The append() function for a list and the add() method for a set should be used to sequentially add each element to the list or set, respectively.

Example:

List = list()
Set = set()
l = int(input("Enter the size of the List : "))
s = int(input("Enter the size of the Set : "))
print("Enter the List elements : ")
for i in range(0, l):
List.append(int(input()))
print("Enter the Set elements : ")
for i in range(0, s):
Set.add(int(input()))
print(List)
print(Set)

Enter the size of the List : 4

Enter the size of the Set : 3

Enter the List elements : 5 6 5 4

Enter the Set elements : 6 8 9 [5, 6, 5, 4] {8, 9, 6}

Using map() and list() / set() methods

 

Example:

List = list(map(int, input("Enter List elements separated by space : ").split()))
Set = set(map(int, input("Enter the Set elements separated by space :").split()))
print(List)
print(Set)

Enter List elements separated by space : 1 2 3 5 6866 2422

Enter the Set elements separated by space :2 5 6 85 654

[1, 2, 3, 5, 6866, 2422]

{2, 5, 6, 654, 85}

 

Taking Input for Tuple

 

Tuples are known to be immutable, meaning there are no ways for adding elements to tuples. A tuple can have additional elements added to it by first typing casting the tuple into a list, adding the element to the list, and then typing casting the list back into a tuple.

Example:

T = (52, 2020, 445, 865, 7456)
print("Tuple before adding new element")
print(T)
L = list(T)
L.append(int(input("Enter the new element : ")))
T = tuple(L)
print("Tuple After adding the new element")
print(T)

Tuple before adding new element

(52, 2020, 445, 865, 7456)

Enter the new element : 258

Tuple After adding the new element

(52, 2020, 445, 865, 7456, 258)

 

Multi-Line input from a user

 

Every time a newline character is seen, the input() method returns (when the user presses Enter key). Therefore, input() will only return the first line if you attempt to send information on several lines.

This may be avoided by using the for-loop. Each iteration receives a single line of input, and we terminate when we reach an empty line (“Press Enter on an empty line”). We create a list out of all of these lines.

Example:

total_input = []
print("Enter employees Names: ")
while True:
name = input()
if name:
total_input.append(name)
else:
break
print('Total input received :')
print(total_input)

Enter employees Names:

Codingal

Amit

Dhanwani

Coding

Penguin

Total input received :

['Codingal', 'Amit', 'Dhanwani', 'Coding', 'Penguin']

 

Function raw_input()

 

The raw input() method is used to collect user input. It reads data from a single line after receiving the input from the Standard input in the form of a string.

Syntax:

raw_input(?statement?)

 

Example:

codingal=raw_input("Enter value:\n ");
print (codingal)

Enter value:

Love

 

Numbers are not directly handled by raw input().

 

Example:

codingal=raw_input("Enter the year in which the codingal started:\n ");

print (codingal)

Enter the year in which the codingal started:

2020

 

Then an error appears because raw input() does not directly handle numbers. Conversion is used while working with numbers.

 

Example:

codingal=int(raw_input("Enter the year in which the codingal started:\n "));
print (codingal)

 

Enter the year in which the codingal started:

2020

Now it will display 2020.

 

Only earlier versions of Python, specifically Python 2.x, use this raw_input () method.

In Python 2.x, there are two functions that accept user values. The input function comes first, followed by the raw input() function.

Developers are advised to use Python 2.x’s raw input function. This is due to a vulnerability in Python version 2.x’s input method.

 

User input in Python and an EOFError example

 

One of the exceptions to handle failures in Python is called EOFError, and it is raised in situations like the interruption of the input() function in Python versions 2.7 and 3.6 as well as later versions, or when the input() function unexpectedly reaches the end of the file in Python version 2.7, meaning the functions do not read any data before the end of the input is reached.

 

Example:

value =input("Please enter an integer:\n")

print(f'You entered {value}')

Enter a value: Traceback (most recent call last):

File “example.py”, line 1, in <module>

value = input(“Please enter an integer: “)

EOFError

 

Python’s EOFError function:

  1. The EOFError class, which serves as the Exception class’s base class, is inherited by the BaseException class.
  2. Technically speaking, EOFError is an exception rather than an error. The EOFError exception is thrown when one of the built-in methods, such input() or read(), produces a string that is empty after reading no data.
  3. The EOFError exception is produced if no data is retrieved and a string is returned, however this exception is raised if our software tries to retrieve anything and make modifications to it.

 

How to Fix the Python EOFError Error:

The input() function does not read any data in the event of an End of File Error, or EOFError, and instead raises the exception EOFError. To avoid triggering this exception, we should try to input something like CTRL + Z or CTRL + D before submitting the End of file exception.

Example:

try:
data = raw_input ("Do you want to continue?: ")
except EOFError:
print ("Error: No input or End Of File is reached!")
data = ""
print data

 

The input provided by the user is being read which is: Hello this is a demonstration of EOFError Exception in Python.

The input provided by the user is being read which is: EOF when reading a line.

Explanation: In the program above, try to prevent the EOFError exception with an empty string, which writes the customized program message that is displayed in the program and publishes the same on the output instead of the End Of File problem message.

In the event that the EOFError exception is handled, the try-and-catch and catch block may be used.

 

User Input Exception Handling

 

The ValueError exception is one of the type-most conversion’s frequent problems.

We receive a ValueError exception when the user inputs information that cannot be translated into the specified type.

 

Example:

For age, the user inputs a random string.

num = int(input('Enter age: '))

The int() method demands an integer value enclosed in a string in this case. An error will be produced by any other kind of value. Take a look at what occurs when we enter “codingal” as input.

Enter age: codingal

Traceback (most recent call last):

  File "main.py", line 1, in <module>

    num = int(input('Enter age: '))

ValueError: invalid literal for int() with base 10: 'codingal'

 

We must address several of these typical user input problems in order to make sure the user provides accurate data. For this, we’ll make use of Python Exception Handling.

 

Example:

try:
    num = int(input('Enter a number: '))
    print('The entered number is: ', num)
except ValueError:
    print('Try Again!!! This is not a number.')

If we once again enter “codingal” as input:

Enter a number: codingal

Try Again!!! This is not a number.

 

If the user provides a non-integer value in the sample above, the code will trigger an exception. The except statement, which prints “Try Again!!! This is not a number.” detects this error.

This try-except block ensures that our program won’t fail in the event of incorrect user input.

If we enter an integer number as input in the same example then we will get the following output:

Enter a number: 2020

The entered number is:  2020

 

The exception block can be used with a loop. The user will thus be asked repeatedly until they provide accurate information.

Example:

while True:
    try:
        num = int(input('Enter a number: '))
        break
        except ValueError:
        print('Invalid Input. Try Again!!! This is not a number')
     print('The entered number is: ', num)

Enter a number: codingal

Invalid Input. Try Again!!! This is not a number

Enter a number: love

Invalid Input. Try Again!!! This is not a number

Enter a number: 2020

The entered number is:  2020

 

Conclusion

After reading this blog, you will get a clear understanding about input in Python.

An easy-to-use framework is provided by Python for gathering user input. A line is received from the console by the input function, which then changes it into a string and returns it.

All data received by the input function is converted into a string format. To transform the input into the desired format, we employ type-conversion.

The try-except block can be used to handle exceptions brought on by incorrect input. Multiple values can be entered on a single line with the use of the split and map functions.

Python is the best programming language to start with. Codingal offers Python for kids course to help your child enhance cognitive, logical, and computational skills. We provide 1:1 live interactive online coding classes for kids with expert coding instructors. Along with lifetime access to course content and downloadable learning resources, to cater to every child’s need by providing a personalized journey.

Coding for kids has many beneficial advantages that develop cognitive abilities as well as enhances communication skills, entrepreneurship skills, and stimulates creativity. Try a free class today!

 

 

 

 

Sign up to our newsletter

Get the latest blogs, articles, and updates delivered straight to your inbox.

Share with your friends

Try a free class