簡體   English   中英

我想在python中的while循環中只打印一次

[英]I want to print something only once in a while loop in python

代碼:

while True:
 text = 'fizz'
 if text == 'fizz':
  print('fizz')
 elif text == 'buzz':
  print('buzz')

如果text = 'fizz'我想打印一次 fizz 並且如果我用 text = 'buzz' 替換text = 'fizz' text = 'buzz'它會打印嗡嗡聲。

使用標志變量來指示是否已打印任何內容。 如果已設置,請勿再次打印。

printed = False
while True:
    text = 'fizz'
    if not printed:
        if text == 'fizz':
            print('fizz')
            printed = True
        elif text == 'buzz':
            print('buzz')
            printed = True

您可以通過多種方式執行此操作:

printed = False
while not printed:
 text = 'fizz'
 if text == 'fizz':
  print('fizz')
  printed = True
 elif text == 'buzz':
  print('buzz')
  printed = True
while True:
 text = 'fizz'
 if text == 'fizz':
  print('fizz')
  break
 elif text == 'buzz':
  print('buzz')
  break

如果你想選擇你的嘶嘶聲程序的結果,請使用input()

版本 1

while True:
    # Each new loop it starts by asking for fizz or buzz
    # If something other than fizz or buzz is typed in
    # the code will print nothing and loop again
    text = input('fizz or buzz?: ')
    if text == 'fizz':
        print('fizz')
    if text == 'buzz':
        print('buzz')
    

如果您希望您的程序每次都在兩者之間切換,請使用此代碼

版本 2

while True:
    text = 'fizz'
    if text == 'fizz':
        text = 'buzz'  # switch fizz for buzz
        print('fizz')
    if text == 'buzz':
        text = 'fizz'  # switch buzz for fizz
        print('buzz')
    # I added a = input() because without it,
    # It would loop hundreds of times a second 
    # printing fizz buzz over and over
    a = input()

如果您希望您的代碼打印一次兩者之一,請使用此代碼

版本 3

def fizz_buzz():
    text = 'fizz'
    if text == 'fizz':
        print('fizz')
    if text == 'buzz':
        print('buzz')


printing = True
while True:
    if printing:
        fizz_buzz()
        printing = False

使用過程使 while 語句更整潔,因為嵌套 if 語句並在 while 循環中加載使其更難閱讀。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM