How to implement multi-line input in Python?

  In Python, we often encounter the need to enter multiple lines of content. In order to save time and reduce repetitive work processes, we need to use the multi-line input function. So how does Python implement multi-line input? The following are common methods.

  1. Use for loop to implement multi-line input

  You can use a for loop to implement multi-line input. The code is as follows:

  ```

  n = int(input())

  arr = []

  for i in range(n):

  arr.append(input())

  print(arr)

  ```

  The above code first inputs an integer n, which means that n rows of data need to be input, and then uses a for loop to traverse n times, adding the input data to the arr list each time. Finally, print the arr list to get the results of multi-line input.

  2. Use while loop to implement multi-line input

  You can also use a while loop to implement multi-line input. The code is as follows:

  ```

  arr = []

  while True:

  s = input()

  if s == '':

  break

  arr.append(s)

  print(arr)

  ```

  The above code uses a while loop to continuously input data until a blank line is entered. Each input data is added to the arr list. Finally, print the arr list to get the results of multi-line input.

  3. Use list generation to implement multi-line input

  You can also use list generation to implement multi-line input. The code is as follows:

  ```

  n = int(input())

  arr = [input() for i in range(n)]

  print(arr)

  ```

  The above code uses list generation to read N rows of data at once. First enter an integer N, which means n rows of data need to be entered. Then use list generation to traverse n times and add the input data to the arr list. Finally, print the arr list to get the results of multi-line input.

  4. Use the split function to implement multi-line input

  You can also use the split function to implement multi-line input. The code is as follows:

  ```

  arr = input().split()

  print(arr)

  ```

  The above code uses the split function to read multiple rows of data at one time. Use the input function to input multiple rows of data, and use the split function to split the multiple rows of data into a list. Finally, print this list to get the result of multi-line input.

Guess you like

Origin blog.csdn.net/oldboyedu1/article/details/135015809