python中是用tab还是空格_关于python:python3不合理地返回TabError:缩进中的制表符和空格使用不一致...

这篇博客讨论了一个新手在Python编程中遇到的问题,即代码因混合使用制表符和空格进行缩进而引发的TabError。作者解释了Python解析器对于一致缩进的要求,并建议程序员在编辑器中配置使用空格代替制表符,以遵循PEP8编码规范。此外,还提到了Python3中混合缩进的语法错误,并提供了处理和预防此类错误的方法。
摘要由CSDN通过智能技术生成

本问题已经有最佳答案,请猛点这里访问。

我是python的新手。 我发现我的python代码不合理地返回了制表符错误:

msgs ['to'] =" xxx@gmail.com"

^

TabError:缩进中的制表符和空格不一致使用

这是我的代码的一部分:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20def send_email(self):

try:

msgs = MIMEMultipart()

msgs['to'] ="xxx"

msgs['from'] ="xxx"

msgs['subject'] ="abc"

msgs.attach(MIMEText(file("~/att1.py").read())

msgs.attach(MIMEText(file("~/att2.docx").read())

server = smtplib.SMTP()

server.connect('smtp.gmail.com:587')

server.login('xxx','xxx')

server.sendmail(msgs['from'], msgs['to'],msgs.as_string())

server.quit()

print"Successfully sent email"

return True

except SMTPException:

print"Error: unable to send email"

print str(SMTPException)

return False

为什么不合理? Pythons解析器是一台机器,它没有原因。 它发现一行使用制表符缩进,而其他行则使用空格。 同上,删除标签。

您的代码确实确实使用了制表符空格。 将原始帖子复制到Sublime Text 3,然后选择所有行时,我可以同时看到制表符(行)和空格(点):

NZqhU.png

请注意,我将制表符设置为扩展到8个空格,这也是Python所做的。 请注意,msgs[..]行现在甚至不再对齐。 在Python 3中混合制表符和空格进行缩进也是语法错误。

配置您的文本编辑器以在使用TAB键时插入空格。 这是Python代码的推荐配置,因为制表符的宽度取决于编辑器的配置,而空格始终是相同的宽度。 这是Python样式指南(PEP 8)的建议:

Tabs or Spaces?

Never mix tabs and spaces.

The most popular way of indenting Python is with spaces only. The second-most popular way is with tabs only. Code indented with a mixture of tabs and spaces should be converted to using spaces exclusively. When invoking the Python command line interpreter with the -t option, it issues warnings about code that illegally mixes tabs and spaces. When using -tt these warnings become errors. These options are highly recommended!

For new projects, spaces-only are strongly recommended over tabs. Most editors have features that make this easy to do.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值