python自学Python

1-Python3从入门到实战—基础之语法

2018-02-02  本文已影响19人  SiberianDante

Python从入门到实战系列——目录

编码格式

# -*- coding=utf-8 -*-
# -*- coding: cp-1252 -*-
^[ \t\v]*#.*?coding[:=][ \t]*([-_.a-zA-Z0-9]+)

标识符

  • 第一个字符必须是字母表中字母或下划线'_';
  • 标识符的其他的部分有字母、数字和下划线组成;
  • 标识符对大小写敏感;

Python保留字

>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', '
def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if',
 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'retu
rn', 'try', 'while', 'with', 'yield']
>>>

注释

# Python单行注释
# 多行注释
# 多行注释
# 多行注释

'''
多行注释
多行注释
多行注释
'''

"""
多行注释
多行注释
多行注释
"""

输出语句

print("Hello World!")
print("Hello",end="")
print("World")

代码块的表示

if True:
    print ("True")
else:
    print ("False")
if True:
    print ("True")
else:
    print ("Answer")
  print ("False")    # 缩进不一致,会导致运行错误

多行语句表示

total = item_one + \
        item_two + \
        item_three
number = ['1', '2', '3',
        '4', '5']

同一行显示多条语句

print ("Hello");print ("World");print ("!");

多个语句构成代码组

if expression : 
   suite
elif expression : 
   suite 
else : 
   suite

空行

数据类型

  • 整数, 如 1
  • 长整数 是比较大的整数
  • 浮点数 如 1.23、3E-2
  • 复数 如 1 + 2j、 1.1 + 2.2j

字符串

name = "SiberiaDante"
name = 'SiberiaDante'
info = ''' name is SiberiaDante,
age is 18,
gender is man'''

info = """ name is SiberiaDante,
age is 18,
gender is man"""
# 输出结果:name is "SiberiaDante"
print("name is \"SiberiaDante\"")
# 输出结果:name is \"SiberiaDante\"
print(R"name is \"SiberiaDante\"")

import 与 from...import

  • 将整个模块(somemodule)导入,格式为: import somemodule
  • 从某个模块中导入某个函数,格式为: from somemodule import somefunction
  • 从某个模块中导入多个函数,格式为: from somemodule import firstfunc, secondfunc, thirdfunc
  • 将某个模块中的全部函数导入,格式为: from somemodule import *
上一篇 下一篇

猜你喜欢

热点阅读