搜索
首页后端开发Python教程Python 中奇怪的&#else&#

The Strange

条件语句中的 else

我们都写过条件语句,并且可能至少使用过一次完整的 if-elif-else 结构。
例如,为所需的浏览器创建 Web 驱动程序实例时:

browser = get_browser()
if browser == 'chrome':
    driver = Chrome()
elif browser == 'firefox':
    driver = Firefox()
else:
    raise ValueError('Browser not supported')

此代码段支持使用 Chrome 和 Firefox 进行测试,如果提供不受支持的浏览器,则会引发异常。

一个鲜为人知的事实是,Python 支持将 else 子句与循环和异常处理结合使用。

Else 带循环

假设我们有一个单词列表,我们想要打印它们,只要它们以大写字母开头。最后,我们要检查是否所有单词都已处理,如果是,则执行特定逻辑。

我们可以使用标志变量 is_all_words_processed,如果遇到无效单词,则将其设置为 False,然后在循环外检查它以执行逻辑。

seasons = ['Winter', 'Spring', 'Summer', 'Autumn']
is_all_words_processed = True
for season in seasons:
    if not season.istitle():
        is_all_words_processed = False
        break
    print(season)

if is_all_words_processed:
    print('All seasons were processed')

Python 允许我们通过将所有单词都有效时的逻辑放入 else 子句中来避免附加变量:

seasons = ['Winter', 'Spring', 'Summer', 'Autumn']
for season in seasons:
    if not season.istitle():
        break
    print(season)
else:
    print('All seasons were processed')

只有当循环自然完成且没有中断时,else 块才会执行。如果循环被break中断,则else子句将不会运行。
这是用 while 循环重写的相同示例。对于 while,else 子句的行为方式相同:

seasons = ['Winter', 'Spring', 'Summer', 'Autumn']
index = 0
while index 



<h3>
  
  
  异常处理中的else
</h3>

<p>else 子句也可以用于异常处理。除了块之外,它必须在所有之后出现。仅当 try 块中没有引发异常时,else 块内的代码才会执行​​。</p>

<p>例如,让我们读取一个包含两列数字的文件并打印它们的商。我们需要处理无效的文件名,而任何其他错误(例如,将值转换为数字或除以零)都会导致程序崩溃(我们不会处理它们)。<br>
</p>

<pre class="brush:php;toolbar:false">file_name = 'input.dat'
try:
    f = open(file_name, 'r')
except FileNotFoundError:
    print('Incorrect file name')
else:
    for line in f:
        a, b = map(int, line.split())
        print(a / b)
    f.close()

在此示例中,try 块仅包含可能引发捕获的异常的代码。
官方文档建议使用 else 块来避免无意中捕获 try 块之外的代码引发的异常。尽管如此,在异常处理中使用 else 可能感觉并不直观。

将 Else 与循环和异常处理相结合

这是我在采访中提出的一个问题。
假设我们有一个带有 find_element 方法的 Driver 类。 find_element 方法要么返回一个元素,要么引发 ElementNotFoundException 异常。在此示例中,它的实现是随机返回一个元素或以相等的概率引发异常。

使用基本的 Python 语法,实现一个方法 smart_wait(self, locator: str, timeout: float, step: float),该方法每步秒检查具有给定定位器的元素。如果在超时秒内找到该元素,则返回;否则,引发 ElementNotFoundException 异常。

browser = get_browser()
if browser == 'chrome':
    driver = Chrome()
elif browser == 'firefox':
    driver = Firefox()
else:
    raise ValueError('Browser not supported')

这是实现此方法的一种方法:

  • 只要超时未到,就会尝试查找元素。
  • 如果找到该元素,则退出循环。
  • 如果没有找到元素,则等待步长间隔。
  • 如果超过超时,则引发 ElementNotFoundException。 这是一个简单的实现:
seasons = ['Winter', 'Spring', 'Summer', 'Autumn']
is_all_words_processed = True
for season in seasons:
    if not season.istitle():
        is_all_words_processed = False
        break
    print(season)

if is_all_words_processed:
    print('All seasons were processed')

我们可以通过使用 return 而不是 break 来稍微缩短逻辑,但现在让我们将其保留为 i 。

其实这个方法是在Selenium的WebDriverWait类中实现的——until方法:

seasons = ['Winter', 'Spring', 'Summer', 'Autumn']
for season in seasons:
    if not season.istitle():
        break
    print(season)
else:
    print('All seasons were processed')

现在,让我们使用 else 重写此方法以进行异常处理和循环:

  1. 异常只能在 self.find_element(locator) 行中引发。如果未引发异常,则应执行退出循环。所以我们可以将break移动到else块。
  2. 如果循环不是因为中断而退出,我们的方法应该引发异常。因此我们可以将异常引发移至循环的 else 子句。
  3. 如果您依次执行转换 1 和 2,您会发现当前时间只能在循环条件下获取。

完成这些转换后,我们获得了一个使用 else 语句进行异常处理和循环的方法:

seasons = ['Winter', 'Spring', 'Summer', 'Autumn']
index = 0
while index 




<hr>

<p>我能说什么...这是 Python 鲜为人知的功能之一。不频繁使用可能会使其在每种情况下使用起来不太直观——这可能会导致混乱。然而,了解它并在需要时有效地应用它无疑是值得的。</p>

<p><strong>新年快乐!</strong>???</p>

<p>P.S.真的很可怕吗?:<br>
我自己写文章,但使用 ChatGPT 翻译它们。为了翻译,我删除了所有代码片段,但 ChatGPT 恢复了所有代码片段?</p>


          

            
        

以上是Python 中奇怪的&#else&#的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
Python:编译器还是解释器?Python:编译器还是解释器?May 13, 2025 am 12:10 AM

Python是解释型语言,但也包含编译过程。1)Python代码先编译成字节码。2)字节码由Python虚拟机解释执行。3)这种混合机制使Python既灵活又高效,但执行速度不如完全编译型语言。

python用于循环与循环时:何时使用哪个?python用于循环与循环时:何时使用哪个?May 13, 2025 am 12:07 AM

useeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.ForloopSareIdeAlforkNownsences,而WhileLeleLeleLeleLoopSituationSituationSituationsItuationSuationSituationswithUndEtermentersitations。

Python循环:最常见的错误Python循环:最常见的错误May 13, 2025 am 12:07 AM

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐个偏置,零indexingissues,andnestedloopineflinefficiencies

对于循环和python中的循环时:每个循环的优点是什么?对于循环和python中的循环时:每个循环的优点是什么?May 13, 2025 am 12:01 AM

forloopsareadvantageousforknowniterations and sequests,供应模拟性和可读性;而LileLoopSareIdealFordyNamicConcitionSandunknowniterations,提供ControloperRoverTermination.1)forloopsareperfectForeTectForeTerToratingOrtratingRiteratingOrtratingRitterlistlistslists,callings conspass,calplace,cal,ofstrings ofstrings,orstrings,orstrings,orstrings ofcces

Python:深入研究汇编和解释Python:深入研究汇编和解释May 12, 2025 am 12:14 AM

pythonisehybridmodelofcompilationand interpretation:1)thepythoninterspretercompilesourcececodeintoplatform- interpententbybytecode.2)thepytythonvirtualmachine(pvm)thenexecuteCutestestestesteSteSteSteSteSteSthisByTecode,BelancingEaseofuseWithPerformance。

Python是一种解释或编译语言,为什么重要?Python是一种解释或编译语言,为什么重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允许fordingfordforderynamictynamictymictymictymictyandrapiddefupment,尽管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

对于python中的循环时循环与循环:解释了关键差异对于python中的循环时循环与循环:解释了关键差异May 12, 2025 am 12:08 AM

在您的知识之际,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations则youneedtoloopuntilaconditionismet

循环时:实用指南循环时:实用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。