你们在使用ChatGPT时,有没有遇见这种,关于代码缩进,他始终搞不明白?


import subprocess# 使用 adb 命令获取手机的存储容量adb_output = subprocess.check_output(['adb', 'shell', 'df']).decode().strip().split('\n')
 
for line in adb_output:
 if '/storage/emulated' in line:
 available_storage = int(line.split()[3]) /1024 print(f'可用存储空间为 {available_storage:.2f} MB')
 break# 查找并删除 .log 文件adb_output = subprocess.check_output(['adb', 'shell', 'find', '/sdcard', '-name', '*.log']).decode().strip().split('\n')
for file_path in adb_output:
 filename = file_path.split('/')[-1]
 print(f'正在删除 {filename}...')
 subprocess.run(['adb', 'shell', 'rm', file_path])
 
print('清理完成!')

img

参考GPT和自己的思路:

这段代码的问题在于第6行的代码缩进不正确。应该将 print 函数的开头与上一行的除了除数的除法运算符之外的部分保持在同一缩进层级,即将第6行的代码修改为:

available_storage = int(line.split()[3]) / 1024
print(f'可用存储空间为 {available_storage:.2f} MB')

这样便可正确输出可用存储空间。同时,该段代码中还存在其他的代码缩进问题,需要一一检查修正。具体来说,第8行和第11行的代码缩进应该向右移动一个层级,使其与第7行和第10行的代码缩进在同一层级。

adb_output = subprocess.check_output(['adb', 'shell', 'find', '/sdcard', '-name', '*.log']).decode().strip().split('\n')
for file_path in adb_output:
    filename = file_path.split('/')[-1]
    print(f'正在删除 {filename}...')
    subprocess.run(['adb', 'shell', 'rm', file_path])

修正后的代码如下所示:

import subprocess

# 使用 adb 命令获取手机的存储容量
adb_output = subprocess.check_output(['adb', 'shell', 'df']).decode().strip().split('\n')

for line in adb_output:
    if '/storage/emulated' in line:
        available_storage = int(line.split()[3]) / 1024
        print(f'可用存储空间为 {available_storage:.2f} MB')
        break

# 查找并删除 .log 文件
adb_output = subprocess.check_output(['adb', 'shell', 'find', '/sdcard', '-name', '*.log']).decode().strip().split('\n')
for file_path in adb_output:
    filename = file_path.split('/')[-1]
    print(f'正在删除 {filename}...')
    subprocess.run(['adb', 'shell', 'rm', file_path])

print('清理完成!')

参考GPT和自己的思路:

这段代码有缩进的问题,需要按照Python语言的规范进行缩进,否则代码会无法运行。可以尝试下面的修改:

import subprocess

# 使用 adb 命令获取手机的存储容量
adb_output = subprocess.check_output(['adb', 'shell', 'df']).decode().strip().split('\n')

for line in adb_output:
    if '/storage/emulated' in line:
        available_storage = int(line.split()[3]) / 1024
        print(f'可用存储空间为 {available_storage:.2f} MB')
        break

# 查找并删除 .log 文件
adb_output = subprocess.check_output(['adb', 'shell', 'find', '/sdcard', '-name', '*.log']).decode().strip().split('\n')

for file_path in adb_output:
    filename = file_path.split('/')[-1]
    print(f'正在删除 {filename}...')
    subprocess.run(['adb', 'shell', 'rm', file_path])

print('清理完成!')

在这个修改的代码中,我们对第2行和第7行进行了缩进的调整,同时对第6行也进行了一个语法错误的修复。现在这段代码应该可以正常运行了。

不是它搞不明白,是你没搞明白
对于python来说,缩进1个空格也行,缩进2个空格也行,4个空格也可以,反正上下对齐就行
你自己的代码只缩进1个空格,那你给chartGPT看,它给你的答案肯定也是缩进1个空格
但是你肉眼又分不清1个空格和不空格有什么区别,这不是自己坑自己吗
你交给它的代码就应该好好的空4个空格再给它看