简体   繁体   中英

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

Code:

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

I want to print fizz once if text = 'fizz' and if I replace text = 'fizz' with text = 'buzz' it prints buzz.

Use a flag variable that indicates whether anything has been printed. Don't print again if it's set.

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

You can do this in multiples ways:

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

If you want to choose the outcome of your fizz buzz program use input()

Version 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')
    

If you want your program to switch between the two each time then use this code

Version 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()

If you want your code to print one of the two once, then use this code

Version 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

Using a procedure makes the while statement a little tidier since having nested if statements and loads in the while loop makes it harder to read.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM