为了账号安全,请及时绑定邮箱和手机立即绑定

我可以在 Python 中使用多少个 if/else 语句

我可以在 Python 中使用多少个 if/else 语句

翻阅古今 2022-06-14 16:47:14
假设我有一些用 Python 2.7 编写的代码,此代码依赖于一个 if 语句为真,然后使用另一个 if 条件和另一个取决于两个最终条件是否为真我可以继续在我的代码中永远这样做还是有一个限制?无论如何我可以做得更好吗?#!/usr/bin/pythonimport osif os.path.isfile('/tmp/EXAMPLE.txt'):    if os.path.getsize('/tmp/EXAMPLE.txt') == 0:        if os.access('/tmp/EXAMPLE.txt', os.W_OK) == True:            DATA = open('/tmp/EXAMPLE.txt', 'w')            if DATA.mode == 'w':                DATA.write('DATA')                DATA.close()                DATA = open('/tmp/EXAMPLE.txt', 'r')                if DATA.mode == 'r':                    if 'DATA' in DATA.read():                        print 'File size is no longer zero'                    else:                        print 'Data failed to write'                else:                    print 'File could not be read from'            else:                print 'File could not written to'        else:            print 'File does not have write permissions'    else:        print 'File has data already'else:    print 'File does not exist'
查看完整描述

1 回答

?
撒科打诨

TA贡献1934条经验 获得超2个赞

你可以继续前进——但你不应该。此代码不可读。相反,您应该反转 if 检查。例如,如果您的代码仅在路径是文件时才有效,则不是:


if os.path.isfile('/path/to/file'):

   # rest of code

你可以这样做:


if not os.path.isfile('/path/to/file'):

    # error handling, reporting, change of control etc.

# rest of code

这是以这种方式“反转”的问题中的一些代码:


#!/usr/bin/python

import os

import sys


if not os.path.isfile('/tmp/EXAMPLE.txt'):

    print('File does not exist')

    sys.exit(1)

if os.path.getsize('/tmp/EXAMPLE.txt') != 0:

    print('File has data already')

    sys.exit(1)


if os.access('/tmp/EXAMPLE.txt', os.W_OK) == False:

    print('File does not have write permissions')

    sys.exit(1)

# rest of the code


查看完整回答
反对 回复 2022-06-14
  • 1 回答
  • 0 关注
  • 264 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号