score = int(input("Please enter a bowling score between 0 and 300: "))
while score >= 1 and score <= 300:
scores.append(score)
score = int(input("Please enter a bowling score between 0 and 300: "))
print(scores)
我希望用戶在回圈中一次輸入 10 個整數,并將所有十個整數存盤在一個名為分數的串列中。
uj5u.com熱心網友回復:
如果您不需要在某個時間間隔內限制輸入的數字,您可以執行以下操作:
scores = []
for i in range(10):
scores.append(int(input())
這將重復等待用戶輸入,并將每個值存盤在scores串列中。如果您希望數字介于 1 和 300 之間,只需將您已有的代碼放入 for 回圈中,或者創建一個計數器。你可能會得到這樣的結果:
scores = []
for i in range(10):
score = 0
while score >= 1 and score <= 300:
score = int(input("Please enter a bowling score between 0 and 300: "))
scores.append(score)
print(scores)
uj5u.com熱心網友回復:
如果假設所有輸入都是有效的,那么您可以簡單地執行以下操作:
scores = [int(input("Please enter a bowling score between 0 and 300: ")) for _ in range(10)]
ValueError但是,如果輸入無法轉換為 int,這將引發 a ,并且它也不會檢查它是否在范圍內。如果您想在無效輸入上重新提示它們,直到您有 10 個有效輸入,您可以將“獲得有效分數”作為自己的函式,然后使用 10 次呼叫來構建串列:
def get_score() -> int:
while True:
try:
score = int(input("Please enter a bowling score between 0 and 300: "))
if not (0 <= score <= 300):
raise ValueError(f"{score} isn't between 0 and 300")
return score
except ValueError as e:
print(f"Error: {e}. Please try again.")
scores = [get_score() for _ in range(10)]
uj5u.com熱心網友回復:
如果您希望用戶在不同的行中輸入,那么這應該有效:
inputList = []
for i in range(10):
inputList.append(input("Enter: "))
但是,如果您希望用戶在同一行中輸入所有值,請使用:
inputList = map(int, input("Enter: ").split())
uj5u.com熱心網友回復:
讓我們做一個不同于“嘗試這個”的方法,因為它看起來像一個初學者。
要詢問用戶輸入,您可以使用該input()功能。它會給你一個字串。要將字串轉換為數字,您可以使用int(),float()或其他函式,具體取決于數字應具有的屬性(十進制數、精度等)。
要重復某個動作,您需要使用回圈。你知道while在你的代碼中看到的。loop 關鍵字可以嵌套,即您可以在回圈內有一個回圈,您可以安排它,以便它檢查數字限制條件之外的數字數量,例如:
mylist = []
while len(mylist) < 10:
num = int(input("some text"))
while <your number condition>:
mylist.append(num)
...
...
或者您可以利用for回圈只執行 N 次代碼塊,例如range(10):
mylist = []
for _ in range(10):
num = int(input("some text"))
while <your number condition>:
mylist.append(num)
...
...
對于while回圈,您需要注意可能無限回圈的情況,因為條件始終為真 - 就像您的情況:
scores = []
score = < a number between 1 and 300, for example 1>
while score >= 1 and score <= 300: # 1 >= 1 and 1 <= 300 <=> True and True
scores.append(score)
score = int(input("Please enter a bowling score between 0 and 300: "))
print(scores)
如果您輸入一個超出間隔的數字,它將退出,但不能保證您想要的 N 次(10 次)。為此,您可能需要稍微調整回圈break以在出現 10 個值后停止執行:
scores = []
score = < a number between 1 and 300, for example 1>
while score >= 1 and score <= 300: # 1 >= 1 and 1 <= 300 <=> True and True
scores.append(score)
score = int(input("Please enter a bowling score between 0 and 300: "))
if len(scores) >= 10:
break # stop the while loop and continue to "print(scores)"
print(scores)
但是,這并不能處理諸如輸入之類的情況,0或者1000假設一旦您從間隔中選擇了數字,while即使分數少于 10 ,它也會停止回圈。
然后很明顯,ValueError當您只按Enter/Return而不輸入數字或提供非數字值(例如twowhich 仍然是數字,但只會崩潰而不是轉換為2with 時)int()。
首先,您需要將數字檢查封裝在其他回圈中或將其重構為如下所示:
mylist = []
while len(mylist) < 10:
num = int(input("some text"))
if num >= 1 and num <= 300:
mylist.append(num)
它甚至可以處理錯誤的數字輸入,例如,1000并會要求輸入另一個數字。
要處理非數字輸入,至少有兩種方法——要么讓它失敗,要么先檢查值:
首先失敗,您將int()自動傳遞無效值,Python 解釋器將生成并引發Exception.
mylist = []
while len(mylist) < 10:
try:
num = int(input("some text"))
except ValueError as error:
# do something with the error e.g. print(error)
# or let it silently skip to the next attempt with "continue"
continue
if num >= 1 and num <= 300:
mylist.append(num)
With value validating you can use isnumeric() method which is present on any string instance (which for your case is the return value of input() function):
mylist = []
while len(mylist) < 10:
num = input("some text")
if not num.isnumeric():
continue
if num >= 1 and num <= 300:
mylist.append(num)
And to make it more compact, you can chain the comparison, though with one unnecessary int() call when the value is correct assuming most of the values are incorrect. In that case num.isnumeric() evaluates to False first and prevents all int() calls while if the input is numberic you end up calling isnumeric() and 2x int():
mylist = []
while len(mylist) < 10:
num = input("some text")
if num.isnumeric() and 1 <= int(num) <= 300:
mylist.append(int(num))
or the other way around, assuming most of the values are correct you can go for the edge-case of incorrect value with try which would be slower afaik but should be faster than always asking whether a string isnumeric().
mylist = []
while len(mylist) < 10:
try:
num = int(input("some text"))
except ValueError:
continue
if 1 <= num <= 300:
mylist.append(num)
每種方法都有自己的權衡。您可以爭取可讀性、性能、緊湊性或任何其他特征,并且根據特征將有一種方法可以衡量它,例如您可能想要使用的性能time.time和可讀性,例如pylint.
額外的一點,如果您正在創建 CLI 工具,您可能想要處理Ctrl C(中斷/終止程式,將引發KeyboardInterrupt)和Ctrl D(結束輸入,將引發EOFError)。兩者都可以用try/處理except。
uj5u.com熱心網友回復:
首先,您必須定義串列“分數”。
while score >= 1 and score <= 300:表示如果輸入值不在 0 到 300 之間,則回圈結束。因此,您可能無法完成 10 個整數的串列。您可以使用if代替來檢查此條件while。
while 回圈需要檢查scores串列是否有 10 個元素。
scores = []
while len(scores) < 10:
score = int(input("Please enter a bowling score between 0 and 300:"))
if (1 <= score <= 300):
scores.append(score)
else:
print("Score must be between 0 and 300")
print(scores)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/376190.html
下一篇:串列中元素的計數未產生預期結果
