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

Time:05-17

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.

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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.

  • Related