我只想在python中偶尔打印一次循环



代码:

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

如果text = 'fizz',我想打印一次气泡,如果用text = 'buzz'替换text = 'fizz',它会打印嗡嗡声。

使用一个标志变量来指示是否打印了任何内容。如果已设置,则不再打印。

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语句更加整洁,因为在while循环中嵌套if语句和加载会使其更难阅读。

相关内容

  • 没有找到相关文章

最新更新