[英]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.