In this article, I will explain the basics of the Input function of Python with some easy-to-understand examples.
Python is one of the most popular programming languages in the world, and it is widely used in various applications. One of the basic concepts in Python is the Input()
function, which allows users to interact with the program by providing input values.
Let’s find out the input function, how it works, and how you can use it effectively in your Python programs.
Before you start, I hope you have Python installed and set up a basic editor. If not, do refer to my below guides:
- How to Install Python 3.11 on Ubuntu/Linux
- How to install Python on Windows
- How to set up the IDLE editor for Python
Table of Contents
Python Input Function
The input function in Python is used to accept user input as a string. It prompts the user to enter a value and waits for the user to provide input. The user’s input is then stored as a string in a variable, which can be used later in the program.
Syntax
input("your message to user")
When you run the input function, it shows the message to the user and waits for input. The cursor waits. Once the user enters input and presses enter, the input function reads the user’s input. The value is stored in the variable you specify.
Let’s see a few examples.
Example 1: Simple Input function usage
The following code snippet takes input and shows the output with an additional string.
your_name = input("Enter your name:")
print("Hello " + your_name)
Output:
Enter your name:arindam
Hello arindam
Example 2: Taking input as integer and float
You can also convert the input as int() or float() at runtime while using input() function. Here is an example.
no_of_books = int(input("Enter total books ordered:")) print ("Total number of books:", no_of_books) price_of_each_book = float(input("Enter unit price:")) print ("Total price:", no_of_books * price_of_each_book)
Output:
Enter total books ordered:5 Total number of books: 5 Enter unit price:10.1 Total price: 50.5
Example 4: Joining lists
You can also use other functions, such as lists, to accept a set of values and convert them as lists in Python. Here’s an example which takes input and converts it to a list. Then used, another set of values and appended to the first list.
# take input for first list list_1 = list(input("Enter numbers for list 1:")) #take input for second list list_2 = list(input("Enter some letters for list 2:")) #loop through the second list and add to first list for j in list_2: list_1.append(j) #print the modified first list print(list_1)
Output:
Enter numbers for list 1:1234 Enter some letters for list 2:ABCD ['1', '2', '3', '4', 'A', 'B', 'C', 'D']
Conclusion
I hope this simple guide clarifies the input() function with several examples. It’s a powerful function to accept values from standard input for simple use cases.