[英]Print statement printing infinitely
password=input("Please enter your chosen password within 8 and 24 letters: ")
while len(password)>8 and len(password)<24:
print("this password is within the given length range")
else:
password=input("Please enter a password within the boundaries: ")
當我運行代碼並且輸入的密碼長度超過8和24時,它只是無限打印“此密碼在給定的長度范圍內”。 我不擅長編碼,我確定我做錯了什么。
您忘記了用於停止循環的break
語句。 並且循環語句有問題,主要是您缺少else
的if
部分。
password=input("Please enter your chosen password within 8 and 24 letters: ")
while True: #will continue until break statement executes
if len(password)>8 and len(password)<24:
print("this password is within the given length range")
break #Quit the loop
else:
password=input("Please enter a password within the boundaries: ")
上面的代碼將一直運行,直到用戶輸入密碼8 < length < 24
。
如果你想不斷地提示他們輸入密碼,你需要像這樣在你的 while 循環中輸入你的提示,並改變周圍的小於和大於符號。
password = ""
while len(password) < 8 or len(password) > 24:
password = input("Please enter your chosen password within 8 and 24 letters: ")
else
僅在您使用break
退出while
循環后才執行(與條件變為假時相反)。 你只是想要
password=input("Please enter your chosen password within 8 and 24 letters: ")
while len(password) < 8 or len(password) > 24:
password=input("Please enter a password within the boundaries: ")
如果您不介意對兩個輸入使用相同的提示,請使用帶有顯式中斷的無限循環:
while True:
password=input("Please enter your chosen password within 8 and 24 letters: ")
if 8 <= len(password) <= 24:
break
您將有效密碼存儲在“密碼”變量中。 while 循環檢查 'password' 是否有效,確認它是有效的,然后繼續運行。 如果用戶輸入無效密碼而不是有效密碼,您希望循環繼續進行。 嘗試:
password=input("Please enter your chosen password within 8 and 24 letters: ")
while len(password)<8 or len(password)>24:
password=input("Please enter a password within the boundaries: ")
print("this password is within the given length range")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.