Beginner

For any program to be useful, you need to be able to take data in. There are many ways of doing that, and you need to decide which way works best for you in a given situation. Data can be obtained from various sources such as user inputs, files such as csv, text, excel files, images, etc.

Python3 is a very flexible programming language that has the support of numerous libraries and its functions that offers us many ways using which we can get the data. In this post, we are going to read about multiple ways using which we can get the data input in Python 3.

Method 1: Getting data from user input using input() function

To get input from the user, Python 3 offers us a built-in function named as the input() function. This function is an updated version of raw_input() that was used earlier in Python 2. input() function helps us to read data from the user input via the keyboard. When the input() keyword is encountered in the program upon execution, the program flow halts automatically asking the user to enter some values using the keyboard.

As soon as the user passes the data and hits the enter key, the data gets saved to the program at some memory location. One interesting feature of Python 3 is that it automatically interprets the type of data that the user passes inside the input() function as ‘string’ type unlike other programming languages like C, C++, Java, where we have to specifically mention the data type for the data which we want to read in our system.

A sample Python3 code to get data from a user using the input() function

name = input ("Enter your name : ")

print("Name entered by the user is: ", name)

# printing data type of input value
print ("Data type of name variable is: ", type(name))
Output:
taking user input using input() function
Working of above code:

In the above-given code snippet, the user is asked to enter his name using the input() function, when the program runs, the executed program halts upon reaching the input() function and asks for name, when the user puts his name and hits ENTER key, the program starts to run again and the value is stored inside name variable. Later we print the value stored inside the name variable and its data type. As discussed earlier, data types comes out to be as string.

Method 2: Taking data input using the command line

In our previous example, if we observe we have taken input from the user when the program was in execution. In this section, we will be having a look at another data input method where we will take input from the command line before our code gets executed. For achieving this, we will be using the command line arguments and the sys module to take data inputs and will be displaying the sum of two numbers. Let’s have a look at the code snippet:

import sys

# printing the list of all the arguments passed on command line
List_args = sys.argv
print(List_args)

# printing the type of the arguments
print (type(sys.argv[0]))
print (type(sys.argv[1]))

# first number
a = sys.argv[1]

# second number
b = sys.argv[2]

print("The sum of both the numbers is: ", int(a) + int(b))
Output:
Working of above code:

In the above written code, we have written a code inside a file named a.py . Inside the file, we import the sys module and use the sys.argv atrribute to print the list of arguments passed on the command line. As can be observed, the first argument will always be the name of the file itself and later the data we want to pass as the arguments. You can use the argparse module to do validation on the inputs.

Also, the data passed is always read in form of string so to add these two numbers in form of string we need to typecast them into integers and then display their sum. You can also have a look at the article about the Click module to see an alternative approach to include command line interfaces.

Method 3: Taking data input using stdin

We can even use the stdin attribute present in the sys module to take data inputs directly from the command line. stdin stands for standard input and it is a standard file-like object using which we can read data inputs. One point to always keep in mind is that it adds up a new line character when we hit the enter button to execute at the end of each sentence. So, we can use the rstrip() function to remove the new line character (‘\n’) from the end. Let’s see a code snippet:

# importing the sys module
import sys

for i in sys.stdin:
    print("data entered by user is: ", i.rstrip())
    if i.rstrip() == 'q':
        break
print ("Program ended successfully")
Output:
taking data input using sys.stdin
Working of above code:

Using sys, stdin, we can read data from user input indefinitely until user stops the execution, so to avoid that we’ve use a conditional expression saying when the user presses ‘q’ button the program will terminate successfully otherwise user can enter data as many times they want.

Method 4: Taking data input using fileinput module

Like we used sys.stdin in the previous section, we can also use the fileinput module to get data from users. As fileinput.input() acts as a stream and it can be used to read data inputs from multiple files as well using a loop. A simple use-case to read data input provided by user can be written as:

# importing the fileinput module
import fileinput

for i in fileinput.input():
    print("data entered by user is: ", i.rstrip())
    if i.rstrip() == 'q':
        break
print ("Program terminated successfully")
Output:
taking data input using fileinput module

Method 5: Taking data input from files

Another common way to get user data is to read it from a file. It is really a convenient way to read a large amount of data in a quick time. The file can be available in various formats like .csv files, .txt files, .json files, .xls files, etc. Python offers us the support of different libraries that helps us to parse data from these files efficiently. In this section, we will see a code to read data from a file.txt file using file handling principles of Python.

Content inside a sample file.txt file
with open("file.txt", "r") as f:
    print(f.read())
Output:
reading the data input from the file
Working of code:

In the above-written code, we first wrote some content inside a sample .txt file, and then we read it using file handling concepts. We opened the file in read mode and read the content inside the file use the f.read() method. It can be verified after matching the content in the file and the output we get on the terminal.

Conclusion

We all understand the importance of taking data inputs and thus in this blog post, we saw some of the common methods using which we can read data inputs from the user in Python3.

Get Notified On Related Posts

Error SendFox Connection: 403 Forbidden

403 Forbidden