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

yipeiwu_com6年前Python基础

在有些情况下,利用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

以上这篇在python中利用try..except来代替if..else的用法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python 字符串和整数的转换方法

数字转成字符串 方法一: 使用格式化字符串: tt=322 tem='%d' %tt tem即为tt转换成的字符串 常用的格式化字符串: %d 整数 %f%F 浮点数 %e%E...

Python matplotlib生成图片背景透明的示例代码

Python matplotlib生成图片背景透明的示例代码

使用matplotlib生成图片,想要背景透明,而且图例部分也显示透明效果,找到了大概的设置方法,特此记录。 # coding=utf-8 # matplotlib背景透明示例图 #...

对Django中内置的User模型实例详解

User模型 User模型是这个框架的核心部分。他的完整的路径是在django.contrib.auth.models.User。 字段 内置的User模型拥有以下的字段: 1、us...

python3 tkinter实现添加图片和文本

python3 tkinter实现添加图片和文本

本文在前面文章基础上介绍tkinter添加图片和文本,在这之前,我们需要安装一个图片库,叫Pillow,这个需要下载exe文件,根据下面图片下载和安装。 下载完后直接双击安装exe,默...

pandas通过loc生成新的列方法

pandas通过loc生成新的列方法

pandas中一个很便捷的使用方法通过loc、iloc、ix等索引方式,这里记录一下: df.loc[条件,新增列] = 赋初始值 如果新增列名为已有列名,则在原来的数据列上改变 i...