1. 程式人生 > 程式設計 >在python中利用try..except來代替if..else的用法

在python中利用try..except來代替if..else的用法

在有些情況下,利用try…except來捕捉異常可以起到代替if…else的作用。

比如在判斷一個連結串列是否存在環的leetcode題目中,初始程式碼是這樣的

# Definition for singly-linked list.
# class ListNode(object):
#   def __init__(self,x):
#     self.val = x
#     self.next = None

class Solution(object):
  def hasCycle(self,head):
    """
    :type head: ListNode
    :rtype: bool
    """
    if head == None:
      return False
    slow =  head
    fast = head.next
    while(fast and slow!=fast):
      slow = slow.next
      if fast.next ==None:
        return False
      fast = fast.next.next
    return fast !=None

在 while迴圈內部,fast指標每次向前走兩步,這時候我們就要判斷fast的next指標是否為None,不然對fast.next再呼叫next指標的時候就會報異常,這個異常出現也反過來說明連結串列不存在環,就可以return False。

所以可以把while程式碼放到一個try …except中,一旦出現異常就return。這是一個比較好的思路,在以後寫程式碼的時候可以考慮替換某些if…else語句減少不必要的判斷,也使得程式碼變的更簡潔。

修改後的程式碼

# Definition for singly-linked list.
# class ListNode(object):
#   def __init__(self,head):
    """
    :type head: ListNode
    :rtype: bool
    """
    if head == None:
      return False
    slow =  head
    fast = head.next
    try:
      while(fast and slow!=fast):
        slow = slow.next
        fast = fast.next.next
      return fast !=None
    except:
      return False

以上這篇在python中利用try..except來代替if..else的用法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。