我正在撰寫一個腳本來檢查輸入單詞的長度是否等于某個數字,如果不是,則再次回圈回到輸入問題。
我使用了以下代碼,
x=input("input a word")
y=len(x)
while y<8 or 8<y:
print("word must have 8
characters")
continue
print("word accepted")
break
但問題是當使用“繼續”回圈時,它不會回圈回到輸入問題。輸入問題也不能寫在 while 回圈中,因為它會給出錯誤“x 未定義”。
那么我怎樣才能回到這里的輸入問題。無論如何要這樣做。
uj5u.com熱心網友回復:
長度已經在while回圈之前分配了,所以你永遠不會得到新的輸入。你必須在while回圈內獲得一個輸入,這樣你才能一次又一次地獲得一個新的輸入。
這可以按您的需要作業:
while True:
x = input("input a word: ")
if len(x) != 8:
print("word must have 8 characters")
continue
else:
print("word accepted")
break
uj5u.com熱心網友回復:
使用 a 的兩種方法while True:
while True:
x=input("input a word: ")
if len(x) == 8:
break
print("word must have 8 characters")
使用遞回:
def get_input():
x=input("input a word: ")
if len(x) == 8:
return x
print("word must have 8 characters")
return get_input()
uj5u.com熱心網友回復:
while True==True:
x=input("input a word")
y=len(x)
if y==8:
print("word accepted")
break
else:
print("word must have 8 characters")
# continue
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/347907.html
