Re: [問題] 終止程序

作者: mantour (朱子)   2014-05-30 01:12:19
※ 引述《aquarius523 (minerva)》之銘言:
: 我想終止程序
: 爬文的結果多是關於while loop、for loop的情況(使用break)
: 但現在我要的是"檢查前一個function的結果,並判斷是否繼續
: 若否 先print一段字串再終止"
: 其中沒有用到loop
: 試過break,都會出問題
: 那該怎麼解決呢?
: 有沒有內建指令?
最簡單的方式是整個用if包起來
...
...
if 符和繼續的條件:
繼續的code
...
...
else:
print <your message>
缺點是如果要做很多次這樣的判斷的話code會有點醜
...
...
if 繼續條件條件一:
...
...
if 繼續條件二:
...
...
if 繼續條件三:
...
...
else:
print <message 3>
else:
print <message 2>
else:
print <message 1>
推文提到用return的方式的話就要把整個code包在一個main function裡
例如
def main():
...
...
if not 繼續條件一:
print <message1>
return
...
...
if not 繼續條件二:
print <message2>
return
...
...
main()
或是用exception來處理
例如:
class Termination(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return repr(self.message)
try:
if not 繼續條件一:
raise Termination(<message1>)
...
...
if not 繼續條件二:
raise Termination(<message2>)
...
...
if not 繼續條件三:
raise Termination(<message3>)
...
...
...
except Termination as message:
print message

Links booklink

Contact Us: admin [ a t ] ucptt.com