pythondowhile循环_在Python中模拟do-while循环? - Emulate a do-while loop in Python?

该博客讨论了如何在Python中实现类似do-while循环的功能,因为Python本身不直接支持这种循环结构。作者遇到了一个问题,即在尝试使用迭代器和异常处理来模拟do-while循环时,代码在遇到StopIteration异常时没有正确退出。解决方案是通过在循环体内捕获StopIteration异常来结束循环。示例代码展示了如何处理这种情况,特别是在处理状态机等需要不断检查输入的场景中。
摘要由CSDN通过智能技术生成

问题:

I need to emulate a do-while loop in a Python program. 我须要在Python程序中模拟do-while循环。 Unfortunately, the following straightforward code does not work: 不幸的是,如下简单的代码不起做用: python

list_of_ints = [ 1, 2, 3 ]

iterator = list_of_ints.__iter__()

element = None

while True:

if element:

print element

try:

element = iterator.next()

except StopIteration:

break

print "done"

Instead of "1,2,3,done", it prints the following output: 而不是“1,2,3,完成”,它打印如下输出: app

[stdout:]1

[stdout:]2

[stdout:]3

None['Traceback (most recent call last):

', ' File "test_python.py", line 8, in

s = i.next()

', 'StopIteration

']

What can I do in order to catch the 'stop iteration' exception and break a while loop properly? 我能作些什么来捕获'stop iteration'异常并正确地打破while循环? oop

An example of why such a thing may be needed is shown below as pseudocode. 如下将伪代码示为可能须要这样的事物的示例。 lua

State machine: 状态机: spa

s = ""

while True :

if state is STATE_CODE :

if "//" in s :

tokens.add( TOKEN_COMMENT, s.split( "//" )[1] )

state = STATE_COMMENT

else :

tokens.add( TOKEN_CODE, s )

if state is STATE_COMMENT :

if "//" in s :

tokens.append( TOKEN_COMMENT, s.split( "//" )[1] )

else

state = STATE_CODE

# Re-evaluate same line

continue

try :

s = i.next()

except StopIteration :

break

解决方案:参考一:

https://stackoom.com/question/37KW/在Python中模拟do-while循环

参考二:

https://oldbug.net/q/37KW/Emulate-a-do-while-loop-in-Python

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值