簡體   English   中英

循環-輸入要列出的數字,不允許使用字母輸入,請按Enter鍵分隔。

[英]Loop - Input numbers to list, don't allow alphabetic input, break out by pressing enter ..?

整整一天都沒有取得任何進展,當然也應該很簡單,但是我是Python的新手。 Google的成長還不是很多,所以這是我的最后選擇!

它應該是一些用於將數字值手動放入列表的基本代碼。 如果在腳本中添加“打印”行,則可以看到輸入的值已成功輸入,但是似乎無法通過輸入空白來添加正確的腳本來打破循環。 目前,如果我進行任何設置以使其中斷,則腳本似乎在運行時凍結,因此我必須完全重置控制台。

我也想知道是否有辦法確保輸入始終是整數? 如果用戶輸入非數字內容,最好使內容更整潔並顯示錯誤消息或其他內容。

這是代碼。

values = []
while True:
    a = raw_input('Enter numeric values. Leave blank to stop: ')
    if a == (??????) :
        break
values.append(float(a)) 

謝謝!

您可以將數字限制為

if a.isdigit():

所以你的功能看起來像

def accept_inputs():
    values = []
    while True:     
        a = raw_input('Enter numeric values. Leave blank to stop: ')
        if a.isdigit():
            values.append(float(a))
        if not a:
            return values

測試

>>> accept_inputs()
Enter numeric values. Leave blank to stop: 5
Enter numeric values. Leave blank to stop: 42
Enter numeric values. Leave blank to stop: 73
Enter numeric values. Leave blank to stop: ab
Enter numeric values. Leave blank to stop: abc
Enter numeric values. Leave blank to stop: 
[5, 42, 73]

字符串具有內置函數isdigit() ,如果所有字符均為數字,則返回true。

要在未輸入任何內容的情況下中斷,請使用len()函數檢測字符串是否為空。

更多信息在這里

您的代碼如下所示:

 if a.isdigit():
     #keep going, and add it to the list
 elif len(a) == 0:
        break #stop the loop

我的方法類似於@CoryKramer,但有一些小的更改

>>> values = []
>>> while True:
       val = raw_input('Enter Number : ')
       if not val:
          print values
       elif val.isdigit():
          values.append(int(val))
       else:
          print 'you have entered non - digit value'

Enter Number : 2
Enter Number : a
you have entered non - digit value
Enter Number : 3
Enter Number : 5
Enter Number : 6
Enter Number : 22
Enter Number : 546
Enter Number : 31s
you have entered non - digit value
Enter Number : 345678
Enter Number : 
>>> values
[2, 3, 5, 6, 22, 546, 345678]

暫無
暫無

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

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