0
点赞
收藏
分享

微信扫一扫

Python 基本语法

代码行

单行代码

每行代码结尾不需要加标点


a = 123

多行换行

多行代码,直接换行


a = 123

b = a + 1

复杂过长的计算、操作可用括号然后缩进换行


income = (gross_wages

         + taxable_interest

         + (dividends - qualified_dividends)

         - ira_deduction

         - student_loan_interest)

可加反斜杠对代码进行换行,程序会认为是一行


s = '我和我的\

祖国'

# 代码换行

with open('test.txt','w') as file_1, \

    open("test2.txt", 'w') as file_2:

   file_2.write(file_1.read())

注释

# 第一个注释

# 第二个注释

print(123)

print(456)  # 第三个注释

'''

这里是一段注释

可以随意写很多行

都不会执行

'''

print ("Hello, World!")

缩进

不同逻辑之前用相同的缩进量表示(其他语言会用括号):


def say():

   print('Hello!')

for x in order:

   if x == 'tom':

       print(x, '好孩子!')

   elif x == 'lucy':

       print(x, '你最漂亮!')

   else:

       print(x, '加油加油你最棒!')

集合缩进:


my_list = [

   1, 2, 3,

   4, 5, 6,

   ]

result = some_function_that_takes_arguments(

   'a', 'b', 'c',

   'd', 'e', 'f',

   )

空行

空一行:用于类成员函数之间,或者用于区分不同逻辑块

空两行:类与类,类与函数,函数与函数之间


class Test(object):

   """Test class,提供通用的方法"""

   def __init__(self):

       """Test的构造器:"""

       pass

   def function1(self):

       pass

   def function2(self):

       pass

def function3():

   pass

同一行显示多条语句

# 可用分号分隔

a = 123; b = a + 1

# 简单 for 和 if 可写在同一行

for i in orders: print(i)

if len(order) > 3:print(order)


举报

相关推荐

0 条评论