网络编程
位置:首页>> 网络编程>> Python编程>> 在python中利用try..except来代替if..else的用法

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

作者:很吵请安青争  发布时间:2023-09-12 17:50:10 

标签: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, 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
   try:
     while(fast and slow!=fast):
       slow = slow.next
       fast = fast.next.next
     return fast !=None
   except:
     return False

来源:https://blog.csdn.net/dpengwang/article/details/85320174

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com