簡體   English   中英

在python中接受輸入直到換行

[英]Accepting input till newline in python

我是python初學者。 只要他/她願意,我就會嘗試接受用戶的輸入。 當單獨按下回車鍵時,程序應該停止接受輸入。

那就是

25
65
69
32 
   #stop here since the enter key was pressed without any input

我想出了以下代碼來做到這一點....

a = []
while 1:

    b = input("->")
    if(len(b)>0):
        a.append(b)
    else:
        break

  1. 有沒有其他有效的“pythonic”方法可以做到這一點?

  2. 雖然這與 python 3.3 完美兼容,但它不適用於 python 2.7(用 raw_input() 函數替換 input() )。 屏幕只是保持沉默,沒有任何反應。 為什么?

  3. 是否有任何內置函數可以將字符串轉換回整數!?

你的方法基本沒問題。 你可以這樣寫:

a = []
prompt = "-> "
line = input(prompt)

while line:
    a.append(int(line))
    line = input(prompt)

print(a)

注意:我沒有包含任何錯誤處理。

至於你的其他問題:

  1. raw_input()應該在 Python 2.7 中類似地工作
  2. int() -- 將給定的參數轉換為整數。 如果不能,它將失敗並顯示TypeError

對於 Python 2.x 版本,只需將input()換成raw_input()

僅出於教育目的,您也可以像這樣以函數式風格編寫它:

def read_input(prompt):
    x = input(prompt)
    while x:
        yield x
        x = input(prompt)


xs = list(map(int, read_input("-> ")))
print(xs)

可能是我所知道的最巧妙的方法(不幸的是,沒有錯誤處理,這就是為什么您在生產中不會經常看到它):

>>> lines = list(iter(input, ''))
abc
def
.
g

>>> lines
['abc', 'def', '.', 'g']

這對iter使用雙參數調用簽名,它調用第一個參數 ( input ) 直到它返回第二個參數(此處為'' ,空字符串)。

你的方式還不錯,雖然它在變體下更常見

a = []
while True:
    b = input("->")
    if not b:
        break
    a.append(b)

實際上,使用breakcontinue是許多人執行單行if的罕見情況之一,例如

a = []
while True:
    b = input("->")
    if not b: break
    a.append(b)

雖然這是正式皺眉(tm)。

  1. idk,這段代碼對我來說看起來不錯。
  2. 它在我的 python 2.7.5 上完美運行,使用 raw_input()
  3. 只需使用 int() 函數:例如, int('121') 將 121 作為整數返回

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM