給定以下模擬具有相應維度的網格的輸入:
totLines = int(input("Indicate the number os lines: "))
totColunms = int(input("Indicate the number of columns: "))
我想檢查輸入是否有效(每個數字必須在 0 到 20 之間)。代碼應該檢查網格的每一行并告訴用戶輸入是否有效,如果不要求另一個輸入。問題是我的代碼只檢查 line1 的第一個數字,line2 的第二個數字,依此類推。例如,在 3x3 網格中,如果我為 line1 輸入以下數字(用空格分隔) - 21 10 10 - 代碼會告訴我輸入無效,但如果我將不正確的數字放在位置 2 - 10 21 10 - 代碼不會發現任何問題。我知道這個問題一定與我如何做回圈有關,但我不明白如何解決這個問題。這很容易做到,但這是我第一次學習編程語言,我還有很多東西要學。謝謝!
for lin in range (1, totLines 1):
print("Line", str(lin))
while True:
sMoves = input("Movement for this line: ")
listMoves = sMoves.split()
listMovesINT = list(map(int, listMoves))
if listMovesINT[lin-1] > 0 and listMovesINT[lin-1] <= 20:
break
else:
print ("Not a valid integer")
continue
uj5u.com熱心網友回復:
我建議將邏輯放在其自己的函式中獲取有效的移動串列,all()用于測驗串列中的所有值(您不需要lin主回圈中的當前值或其他任何內容來解決這個問題,并將這個任務放在它自己的函式中可以更容易地專注于它,而不會意外地混入程式的其他部分):
def get_movement() -> list[int]:
"""Get a list of movement values between 1 and 20."""
while True:
try:
moves = [int(n) for n in input("Movement for this line:").split()]
if not all(1 <= n <= 20 for n in moves):
raise ValueError("all values must be between 1 and 20")
return moves
except ValueError as e:
print("Not a valid integer:", e)
然后在你的主回圈中你可以這樣做:
for lin in range (1, totLines 1):
print("Line", lin)
moves = get_movement()
# do whatever thing with moves
uj5u.com熱心網友回復:
正如您所注意到的,您正在將輸入中的專案“系結”到您的“ board ”(類似于“ board ”......totLines變數)。
但是您真的只想一次驗證一個輸入,對嗎?當用戶為任何給定的行撰寫動作集時,它是用于“板”的第一行還是最后一行并不重要。也許您希望行索引顯示一個很好的提示訊息,但僅此而已。在確保輸入有效時,您真的不需要任何線路,不是嗎?
所以這一切都歸結為驗證任何給定行的輸入是否有效,并一直糾纏用戶直到他們(全部)是有效的。就像是:
valid_input = False
while not valid_input:
sMoves = input("Movement for this line: ")
listMoves = sMoves.split()
listMovesINT = list(map(int, listMoves))
valid_input = all((0 < move <= 20) for move in listMovesINT)
if not valid_input:
print("One of the movements is not valid")
如果你想使用總行數totLines(forwhile not valid_input
totLines = int(input("Indicate the number os lines: "))
for lineNum in range(1, totLines 1):
valid_input = False
while not valid_input:
sMoves = input(f"Movement for line {lineNum}: ")
listMoves = sMoves.split()
listMovesINT = list(map(int, listMoves))
valid_input = all((0 < move <= 20) for move in listMovesINT)
if not valid_input:
print("One of the movements is not valid")
uj5u.com熱心網友回復:
首先,您的代碼每行只檢查一個整數。
您有一個索引,但它是行索引 (lin-1),而不是數字索引。
“while True”是否應該迭代數字。如果是,它應該在“split()”之后。
這是一個作業示例:
matrix = []
totlines=3
for i in range( totlines):
line = input( "... ")
numbers = [ int( text) for text in line.split()] # convert list of asciiNumbers to list of 3 integers
for number in numbers:
if (number <= 0) or (number>20):
print( "Invalid number in line", i, ":", numbers)
matrix.append( numbers)
print( matrix)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/519810.html
標籤:Python循环
上一篇:倒計時用戶輸入
