[英]How do I make 'continue' statement iterate the “mother” loop outside of loop where the statement is found? (Python)
[英]How do I stop a print statement in a for loop from printing repeatedly if the loop needs to continue running?
我的代碼中的情況使得即使尋找了一段時間,我也找不到適用的答案。 這是我的代碼的簡化版本:
value = int(input())
list = [5,10,15,20]
for i in list:
if i == value:
print("Value is in list.")
break
else:
print("Value is not in list.")
如果我輸入 15,代碼將打印
“值不在列表中。值不在列表中。值在列表中。”
但我只希望它打印“值在列表中”。 如果它在列表中,則打印一次“值不在列表中”。 一次,如果不是。 我必須保留 for 循環和 if/else 語句。 據我所知,如果不完全結束循環,我就不能在 else 中使用break
。 我該怎么辦?
您可以使用一個標志,該標志默認為 False,如果找到該值,則將該標志設置為 True。
for
迭代完成后,可以查看flag變量的值來判斷該值是否在列表中
value = int(input())
list = [5,10,15,20]
found = False
for i in list:
if i == value:
found = True
break
if found:
print("Value is in list.")
else:
print("Value is not in list.")
這是一種更新算法並使其工作的方法,否則您可以使用if value in list
來檢查元素是否在您的列表中
這可能不是您的目標,但您不能一次檢查列表中是否存在該值,而不是迭代嗎?
value = int(input())
_list = [5,10,15,20]
if value in _list:
print("Value is in list.")
else:
print("Value is not in list.")
您可以創建一個 boolean。
value = int(input())
list = [5,10,15,20]
firstTime = True
for i in list:
if i == value and firstTime == True:
print("Value is in list.")
firstTime = False
else:
if firstTime == True
print("Value is not in list.")
firstTime = False
您可以將其移至 function,它可以隨時終止。
def isin(val):
list_ = [5, 10, 15, 20]
for i in list_:
if val == i:
print("Value in list")
return
print("Value not in list")
isin( int(input()) )
您可以聲明一個 boolean 變量,如下所示:
value = int(input())
list = [5,10,15,20]
avail=False
for i in list:
if i == value:
avail=True
break
if avail:
print('Value in List')
else:
print('Value not in List')
更簡單的方法是使用in
關鍵字,如下所示:
value = int(input())
list = [5,10,15,20]
if value in list:
print('Value In list')
else:
print('Value Not in list')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.