程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python tutorial of the input and output (3) -- in Python multiple input from the user

編輯:Python

Developers often expect users to enter multiple values ​​or inputs in a single line.在 C++/C 中,用戶可以使用 scanf Get multiple inputs in one line,但在 Python 中,There are two ways for the user to get multiple values ​​or inputs in a row.

  • 使用 split() 方法
  • 使用列表理解

使用 split() 方法: 
This function helps to get multiple inputs from the user.It breaks the given input by the specified delimiter.If no delimiter is provided,then any spaces are delimiters.通常,用戶使用 split() method to split Python 字符串,But it can be used to get multiple inputs.

語法 :

input().split(separator, maxsplit)

例子 :

展示了如何使用 split for multiple inputPython 程序

Accepts two inputs at a time

x, y = input("Enter two values: ").split()print("Number of boys: ", x)print("Number of girls: ", y)print()

Accepts three inputs at a time

x, y, z = input("Enter three values: ").split()print("Total number of students: ", x)print("Number of boys is : ", y)print("Number of girls is : ", z)print()

Accepts two inputs at a time

a, b = input("Enter two values: ").split()print("First number is {} and second number is {}".format(a, b))print()

Accepts multiple inputs at once

# and type casting using list() functionx = list(map(int, input("Enter multiple values: ").split()))print("List of students: ", x)

輸出:

使用列表推導: 
List comprehensions are in Python An elegant way to define and create lists in .We can create a list in just one line like a math statement.It is also used to get multiple inputs from the user.

例子:

Shows how to use list comprehensions to get multiple inputsPython 程序

Accepts two inputs at a time

x, y = [int(x) for x in input("Enter two values: ").split()]print("First Number is: ", x)print("Second Number is: ", y)print()

Accepts three inputs at a time

x, y, z = [int(x) for x in input("Enter three values: ").split()]print("First Number is: ", x)print("Second Number is: ", y)print("Third Number is: ", z)print()

Accepts two inputs at a time

x, y = [int(x) for x in input("Enter two values: ").split()]print("First number is {} and second number is {}".format(x, y))print()

Accepts multiple inputs at once

x = [int(x) for x in input("Enter multiple values: ").split()]print("Number of list is: ", x)

輸出 :

注意: The above example takes space-separated input.Use commas if we wish to enter (, ) 分隔,We can use the following:

# Accepts multiple inputs at once,用逗號分隔x = [int(x) for x in input("Enter multiple value: ").split(",")]print("Number of list is: ", x)

感謝大家的閱讀,有什麼問題的話可以在評論中告訴我.希望大家能夠給我來個點贊+收藏+評論 ,你的支持是海海更新的動力!後面我會持續分享前端 & 後端相關的專業知識.


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved