In this tutorial, we will cover the basics of Python Input/Output and also how to import a module in a Python program. Previously we learned about Python Datatypes.
Table of Contents
Basic Input/Output Using Python
I/O means Input and Output. We will learn about the basic input and output functions below. Let’s start out!
How to Read User Input in Python with the input() function?
To accept user input in Python, you need to use the input() function.
With the input() function, you can read from the keyboard input until a line feed is given ( i.e. until you hit the Enter key).
#takes input from keyboard and stores in a string str = input("Enter your input: "); #then we can print the string print(str)
If you run this program you will see a prompt like the below picture, waiting for you to give input. The user can enter multiple characters until they hit the enter key.
How to Print Output In Python?
We are already familiar with the
print() function. We use the print() function to print output to the screen.
print("Print something to the screen")
Moreover, we can pass two or more different strings in the print function separated by either commas (,) or plus (+) signs. Like this;
print("This is first String " + "Followed by this string"); #Or can be written like this also print("This is another String " , "Followed by another string");
Process the user inputs in Python by importing modules
Now moving on from the Python inputs and outputs, how do we process the data that is entered as input by the user?
We need certain functionality to the code. And for the same, we have two options:
- Build the functionality from scratch
- Use existing libraries to extend our program
Python is so widely accepted, using libraries is the easiest and the most preferred route. Python offers hundreds of thousands of libraries to work with.
So let’s work with the user input in Python with some added functionality.
Suppose the user inputs a number and we want our code to output the square root of the number. Now there’s a sqrt() function available Python.
But if we use the function directly, there will be an error as shown in the output below:
#get a variable having value 16 number=16 #square root this number. number=sqrt(number) print(number)
This is because,
sqrt() function is under module name “math”.
If we want to use this function, we need to make this module accessible by importing the module. So, let’s see how importing the module will provide added functionality for our code here.
#first import math module import math #get a variable having value 16 number=16 #square root this number. number=math.sqrt(number) print(number)
If you run this code, you’ll get the square root of the number 16 which is 4.
Awesome! I hope you learned all the basics you need to accept user input in Python and print the required outputs for the same.
We have also learned how we can import certain modules in Python to extend the functionality of our code and work with the inputs.