首页 > 编程语言 >Python - else 语法总结

Python - else 语法总结

时间:2023-03-10 14:36:41浏览次数:30  
标签:try Python except else 语法 print 执行 分支

else 使用汇总。

问题

阅读别人代码,有点疑惑,精简后如下:

def code_example(arg=None):
    for i in range(5):
        if arg:
            break
    else:
        print('else branch')

循环语句后面直接跟了 else 语句,未报错,程序正常运行。一般 else 都是配合判断语句用,那么这里的 else 是什么作用呢

尝试

for i in range(2):
    print(i)
else:
    print("else branch")

>>>
0
1
else branch

test01:根据打印信息发现,for 循环正常执行完成后执行了 else 分支;

for i in range(2):
    continue
else:
    print("else branch")

>>>
else branch

test02:循环体内增加 continue 跳出,执行完成循环后,正常执行 else 分支;

for i in range(2):
    break
else:
    print("else branch")

>>>

test03:如果 break 掉循环,打断循环,没有任何输出,也就是不走 else 分支;

def test():
    for i in range(2):
        return
    else:
        print("else branch")

>>>

test04:尝试 return 语句,打断循环,也是不走 else 分支。

结论
for … else …

  • 仅当循环体全部执行完成,才执行 else 分支;
  • 当循环过程被打断,则不执行 else 分支。

扩展
Python 支持 else 语句汇总:

  • for … else …
  • while … else …
  • try … except … else …
  • if … elif … else …

while
与 for 循环相同步骤测试,结论一样

try

  1. 当 try 内无异常执行完成后,执行 else 分支;
  2. 当 try 内出现异常,执行到 except,不再执行 else 分支。
def test_01():
    try:
        print("try")
    except:
        print("except")
    else:
        print("else")

>>>
try
else
-----------------------
def test02():
    try:
        5 / 0
    except:
        print("except")
    else:
        print("else")

>>>
except

总结

  • for、while 循环
    当循环语句全部正常执行完成(包括 continue),会继续执行 else 分支;当循环语句被打断(break\return),不再执行 else 分支
  • try 异常处理
    当 try 语句无异常执行完成时,会继续执行 else 分支;当抛出异常后,不再执行 else 分支
  • if 条件判断
    不符合 if 或者 elif,才执行 else 分支

标签:try,Python,except,else,语法,print,执行,分支
From: https://www.cnblogs.com/abeelan/p/17203220.html

相关文章

  • Python - 连接数据库
    python连接数据库操作pymysqlimportpymysqldefget_connect():connect=pymysql.connect( host="xxx.com",port=3306,user="test",......
  • Python - pandas 数据处理
    数据处理pandas数据读取pd.read_csv:csv/tsv/txt用逗号、tab分隔的纯文本文件pd.read_excel::微软xls或者xlsx文件pd.read_sql:mysql关系型数据库pd.rea......
  • Python -gdb 查看程序堆栈详情
    MacPython3.7https://www.modb.pro/db/454999安装#搜索仓库$brewsearchgdb#安装$brewinstallgdbError:[email protected]:thebottleneedstheAppleCom......
  • Python - 项目包管理 requirements
    python项目中的依赖库,可以创建一个requirements.txt文件来管理。allure-pytest=2.12.0pytest=7.2.0pytest-rerunfailures=10.3pytest-sugar=0.9.6#安装$pipinst......
  • Python - 获取调用者的函数名称
    def_is_page(self,locator):"""判断是否到达指定页面"""caller_name=traceback.extract_stack()[-2][2]is_page=self.ele_actions(locator).exists()......
  • Python - Crypto 导入失败问题解决记录
    python3.7Mac安装psycopg2$pipinstallpsycopg2...Error:pg_configexecutablenotfound....出现报错:Error:pg_configexecutablenotfound.解决参考:h......
  • Python - pip 报错记录
    #安装包出现错误$pipinstall-rrequirements.txt-ihttp://pypi.douban.com/simple/ERROR:Couldnotfindaversionthatsatisfiestherequirementpbr(from......
  • python 提取csv内容脚本
    目录python提取csv内容脚本python提取csv内容脚本提取csv的内容脚本,这里只是提取了单个csv文件的内容,也没有写入新的文件,也没有把数据处理成json,临时模版,比较简陋,方便......
  • Python gdal读取MODIS遥感影像并结合质量控制QC波段掩膜数据
      本文介绍基于Python中GDAL模块,实现MODIS遥感影像数据的读取、计算,并基于质量控制QC波段进行图像掩膜的方法。  前期的文章PythonGDAL读取栅格数据并基于质量评估波......
  • 实验1 Python开发环境使用和编程初体验
    实验任务1“关于print”task1_1:实验源码:#task1_1print的使用print('hey,u')#输出单个字符串或者单个变量print('hey','u')x,y,z=1,2,3print(x,y,z)#输出多......