- Python Input – How to Read Single and Multiple Inputs
- Single Input
- Multiple Inputs
- Multiple Inputs on a Single Line
- Multiple Inputs from Multiple Lines
- Primary Sidebar
- Categories
- Python input many lines
- # Table of Contents
- # Multiple lines user Input in Python
- # Read user Input until EOF in Python
- Input Multiple Lines in Python
- Using the raw_input() Function to Get Multi-Line Input From a User in Python
- Using sys.stdin.read() Function to Get Multiline Input From a User in Python
- Related Article — Python Input
- Как ввести несколько строк в python
Python Input – How to Read Single and Multiple Inputs
With Python, input can be requested from the user by typing input() . This input will usually be assigned to a variable, and it’s often best to have a user-friendly prompt when requesting the input.
If you’re expecting a specific type of input, such as an integer, it’s useful to perform an explicit conversion on the input before storing it in your variable.
For example, an explicit conversion to an int :
integer_input = int(input(«Please enter an integer between 1 and 10»))
Throughout this guide, you’ll find a wide range of code samples for retrieving input from a user.
Single Input
Retrieving a single input from the user is a good starting point. The code below shows how to request a single input, convert it, and assign it to a variable. We’ll then confirm that the conversion was successful by checking the data type of the variable.
Example 1: Simple single input requests from user
# Explicit conversion to each of the 4 primitive variable types in Python: # These are: String, Int, Float, Boolean # Simple string input string_input_1 = input("Please type your first name: ") print("Name is <>. Data Type: <>".format(string_input_1, type(string_input_1))) # Simple string input string_input_2 = str(input("Please type your first name: ")) print("Name is <>. Data Type: <>".format(string_input_2, type(string_input_1))) # Simple integer input integer_input = int(input("Please type a number between 1 and 10: ")) print("Number is <>. Data Type: <>".format(integer_input, type(integer_input))) # Simple float input float_input = float(input("Please type a decimal between 1 and 2: ")) print("Decimal is <>. Data Type: <>".format(float_input, type(float_input))) # Simple Boolean input bool_input = bool(input("Please type true or false: ")) print("Boolean is <>. Data Type: <>".format(bool_input, type(bool_input)))
Output: Please type your first name: Daniel Name is Daniel. Data Type: Please type your first name: Daniel Name is Daniel. Data Type: Please type a number between 1 and 10: 5 Number is 5. Data Type: Please type a decimal between 1 and 2: 1.67 Decimal is 1.67. Data Type: Please type true or false: true Boolean is True. Data Type:
Multiple Inputs
There are many situations where you may need to read in multiple inputs from a user. One example is where a user will enter a number on the first line, representing how many lines of data they plan to enter next.
This is a common feature of Python coding questions on sites such as HackerRank, so we’ll build up to demonstrating one of these in our examples.
Multiple Inputs on a Single Line
By comma separating multiple calls to input() , we’re able to display multiple prompts to the user, and store the responses in variables.
Example 1 shows two inputs; one integer and one string. The integer is assigned to var1 and the string is assigned to var2 .
Example 1: Retrieve 2 inputs from the user and assign to variables
# Create the variables and assign the user inputs var1, var2 = (int(input("Enter an integer: ")), input("Enter a string: ")) # Input provided by user: # ----------------------- # Enter an integer: 1 # Enter a string: test # Display the inputs entered by the user print("var1 = \nvar2 = ".format(var1, var2))
Output: var1 = 1 var2 = test
Example 2 shows two inputs; one integer and one being a collection of strings separated by spaces. The integer is assigned to var1 and the collection of strings is split into a list, before being assigned to var2 .
Example 2: Retrieve 2 inputs, one being a collection of strings
# Create the variables and assign the user inputs var1, var2 = (int(input("Enter an integer: ")), input("Enter strings separated by a space: ").split()) # Input provided by user: # ----------------------- # Enter an integer: 1 # Enter a string: This is a split string. # Display the inputs entered by the user print("var1 = \nvar2 = ".format(var1, var2))
Output: var1 = 5 var2 = ['This', 'is', 'a', 'split', 'string.']
Multiple Inputs from Multiple Lines
Now we’re going to look at a more complex example. This is taken from the Collections.namedtuple() problem on HackerRank.
Collections.namedtuple() Task:
In short, we’re looking for 3 main inputs:
- Input 1: The number of lines of data to be entered
- Input 2: The column names for the data
- Input 3: The data
So, using what we’ve learned about input() , let’s look at how this can be solved.
Step 1: Get Input 1 and Input 2
The first input will be the number of lines of data to accept after the column names. We’ll store this in the students variable.
The second input will be a series of space-separated strings, to be used as the column names. We’ll store this in the column_names variable.
# Assign our first 2 inputs to their variable names (students, column_names) = (int(input("No. of students: ")), input("Column Names:\n").split())
The list we created by splitting Input 2 now contains the column names. We can pass this to the field_names parameter of our named tuple.
# Create the Grade named tuple Grade = namedtuple('Grade', column_names)
You can find out more about named tuples and their use cases in our guide to the Python collections module.
Step 3: Prompt user for data rows
This is the step that requires most of the logic.
We know how many lines of data to expect from Input 1, which we stored in the students variable. This is how many times we’ll need to send the input prompt to the user.
We also know how many fields of data to expect, and that we can split the input on white space, same as we did for the field names.
- Iterate students number of times
- At each iteration, prompt the user for input
- At each iteration, split this input and assign values to the fields of our Grade named tuples
- Store the MARKS values in an object that can easily be used to find the average
This can all be done with a single line:
# Create a list of MARKS collected from user input marks = [int(Grade._make(input().split()).MARKS) for _ in range(students)]
So, now we have a list containing all our MARKS, the easy part is calculating the average, by dividing the sum by the len .
# Calculate the average mark print("\nAverage Grade = <>".format((sum(marks) / len(marks))))
So, let’s combine steps 1 to 4 and check that our code produces the correct output.
from collections import namedtuple (students, column_names) = (int(input("No. of students: ")), input("Column Names:\n").split()) Grade = namedtuple('Grade', column_names) marks = [int(Grade._make(input().split()).MARKS) for _ in range(students)] print("\nAverage Grade = <>".format((sum(marks) / len(marks))))
Output: No. of students: 5 Column Names: ID MARKS NAME CLASS 1 97 Raymond 7 2 50 Steven 4 3 91 Adrian 9 4 72 Stewart 5 5 80 Peter 6 Average Grade = 78.0
Passionate about all things data and cloud. Specializing in Python, AWS and DevOps, with a Masters degree in Data Science from City University, London, and a BSc in Computer Science.
Primary Sidebar
Categories
- AWS (4)
- Concepts (1)
- Control Flow (1)
- Data Structures (9)
- HackerRank (1)
- Input and Output (1)
- LeetCode (1)
- Modules (1)
- Operators (1)
- Python (2)
Python input many lines
Last updated: Feb 20, 2023
Reading time · 3 min
# Table of Contents
# Multiple lines user Input in Python
To take multiple lines of user input:
- Use a while loop to iterate for as long as the user is typing in values.
- On each iteration, append the user input and a newline character to a list.
- If the user presses Enter without typing in a value, break out of the loop.
Copied!lines = [] while True: user_input = input() # 👇️ if user pressed Enter without a value, break out of loop if user_input == '': break else: lines.append(user_input + '\n') # 👇️ prints list of strings print(lines) # 👇️ join list into a string print(''.join(lines))
We used a while loop to iterate for as long as the user is typing in values.
On each iteration, we check if the user pressed Enter without typing in a value to exit out of the while True loop.
This can be any other condition, e.g. you might have a stop word such as done or quit .
The break statement breaks out of the innermost enclosing for or while loop.
If the user types in a value, we use the list.append() method to append the value and a newline character to a list.
The list.append() method adds an item to the end of the list.
# Read user Input until EOF in Python
Alternatively, you can use the sys.stdin.readlines() method to read user input until EOF.
The readlines() method will return a list containing the lines.
The user can press CTRL + D (Unix) or CTRL + Z (Windows) to exit.
Copied!import sys # 👇️ User must press Ctrl + D (Unix) or Ctrl + Z (Windows) to exit print('Press CTRL + D (Unix) or CTRL + Z (Windows) to exit') user_input = sys.stdin.readlines() # 👇️ get list of lines print(user_input) # 👇️ join the list items into a string print(''.join(user_input))
stdin is used for interactive user input.
Input Multiple Lines in Python
- Using the raw_input() Function to Get Multi-Line Input From a User in Python
- Using sys.stdin.read() Function to Get Multiline Input From a User in Python
The program sometimes may require an input that is vastly longer than the default single line input. This tutorial demonstrates the various ways available to get multi-line input from a user in Python.
Using the raw_input() Function to Get Multi-Line Input From a User in Python
The raw_input() function can be utilized to take in user input from the user in Python 2. However, the use of this function alone does not implement the task at hand. Let us move on to show how to implement this function in the correct way in Python.
The following code uses the raw_input() function to get multi-line input from a user in Python.
x = '' # The string is declared for line in iter(raw_input, x): pass
Further, after the introduction of Python 3, the raw_input() function became obsolete and was replaced by the new input() function.
Therefore, if using Python 3 or higher, we can utilize the input() function instead of the raw_input() function.
The above code can be simply tweaked in order to make it usable in Python 3.
x = '' # The string is declared for line in iter(input, x): pass
Using sys.stdin.read() Function to Get Multiline Input From a User in Python
The sys module can be imported to the Python code and is mainly utilized for maintaining and manipulating the Python runtime environment.
The sys.stdin.read() function is one such function that is a part of the sys module and can be utilized to take multi-line input from the user in both Python 2 and Python 3.
import sys s = sys.stdin.read() print(s)
The Python console can be cleared after taking the input and displayed on the screen using the print command.
Vaibhhav is an IT professional who has a strong-hold in Python programming and various projects under his belt. He has an eagerness to discover new things and is a quick learner.
Related Article — Python Input
Как ввести несколько строк в python
Функция input() ждёт, пока пользователь нажмёт на клавишу Enter, и затем возвращает введенную строку. Значит, нельзя 1 командой input() ввести более одной строки, но можно повторять это, например, в таком цикле:
result = [] while True: # False - пустая строка seq = input('Введите строку: ') if seq: result.append(seq) else: break # run. # 1 # Hello # True # print(result) # => ['1', 'Hello', 'True']
Ввод окончится при двойном переносе строки. В результате получим массив введенных строк.