[英]how can i print something in a for loop only once
我正在制作一個劊子手游戲,我是初學者,我不知道如何讓 for 循環只打印一次:
for char in word:
if char in guesses:
print (char)
print("correct!")
else:
print("_")
所以只想打印一次“正確”,但現在每次插入正確的字母時都會打印它
您可能會提供有關您的代碼和輸入的更多信息。 但是,也許這會有所幫助:
x=[1, 2, 3, 4, 1, 1, 2, 4, 3, 5]
for i in (x):
if i ==1:
found=True
print ("correct!")
break
else:
print ("_")
“break”可以停止循環
您可以使用 boolean 來避免在循環中多次打印內容:
printed = False
for char in word:
if char in guesses:
print (char)
if not printed:
print("correct!")
printed = True
else:
print("_")
如果最后的猜測是在單詞中,這將打印"correct"
,然后是 output 典型的劊子手字符串。
if guesses[-1] in word:
print("correct!")
print(''.join(c if c in guesses else '_' for c in word))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.