基本语法
1.注释
Python中单行注释以 # 开头,
多行注释可以用多个 # 号,还有 ‘’’ 和 “”":
print('hello,python') #这是一个单行注释
print('hello,world!') '''
第一行注释
第二行注释
.. '''
2.标识符
第一个字符必须是字母表中字母或下划线 _ 。
标识符的其他的部分由字母、数字和下划线组成。
标识符对大小写敏感,
方法主要有驼峰命名,帕斯卡命名(大驼峰),下划线命名等;
关键词不能做变量名,关键词查询:
import keyword
key_list = keyword.kwlist
print(key_list)
输出
['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', 'return', 'try', 'while', 'with', 'yield']
3.行与缩进
python最具特色的就是使用缩进来表示代码块,不需要使用大括号 {} 。
缩进的空格数是可变的,但是同一个代码块的语句必须包含相同的缩进空格数。实例如下:
@classmethod
def countryInfo(cls): #正确示例
print('国籍是,',cls)
@classmethod
def countryInfo(cls): #错误示例,缩进不一致
print('国籍是,',cls)
报错:
IndentationError: unexpected indent
4.多行语句
count1 = 'item_one'+'item_two'+\
'item_three' #反斜杠实现多行语句
count2 = ['item_one','item_two',
'item_three' ] #在 [], {}, 或 () 中的多行语句,不需要使用反斜杠(\)
变量和类型
1.字符串
- python中单引号和双引号使用完全相同。
- 使用三引号(’’'或""")可以指定一个多行字符串。
- 转义符 ‘’
- 反斜杠可以用来转义,使用r可以让反斜杠不发生转义。。 如 r"this is a line with \n" 则\n会显示,并不是换行。
- 按字面意义级联字符串,如"this " "is " "string"会被自动转换为this is string。
- 字符串可以用 + 运算符连接在一起,用 * 运算符重复。
- Python 中的字符串有两种索引方式,从左往右以 0 开始,从右往左以 -1 开始。
- Python中的字符串不能改变。
- Python 没有单独的字符类型,一个字符就是长度为 1 的字符串。
- 字符串的截取的语法格式如下:变量[头下标:尾下标:步长]
以下是实例:
user_name = input('输入用户名字:') #input直接输入
user_loc = input('输入你的地理位置:')
print('用户名:%s,地址:%s'%(user_name,user_loc))
string1 = 'helloWorld'
print(string1[0:2]) #左边闭合右边开区间
print(string1[0]) #输出第几个位置的字符
print(string1[1:]) #从第二个位置到结尾
print(string1[0:-1]) #从第一个位置到倒数第二个
print(string1[::2]) #第三位参数表示步长,每两位取一位
print(string1[::-2]) #负号表示从后往前取
print(string1 + '你好')
print('hello\nrunoob')
print(r'hello\nrunoob') #前面添加r,不转译直接输出,r指raw即raw string
输出结果为:
输入用户名字:uzi
输入你的地理位置:hangzhou
用户名:uzi,地址:hangzhou
he
h
elloWorld
helloWorl
hlool
drWle
helloWorld你好
hello
runoob
hello\nrunoob
2.print输出
print 默认输出是换行的,如果要实现不换行需要在变量末尾加上 end="":
实例:
print('a',end = ' ')
print('b',end = ' ')
输出:
a b
3.标准数据类型
Python3 中有六个标准的数据类型:
Number(数字)
String(字符串)
List(列表)
Tuple(元组)
Set(集合)
Dictionary(字典)
Python3 的六个标准数据类型中:
不可变数据(3 个):Number(数字)、String(字符串)、Tuple(元组);
可变数据(3 个):List(列表)、Dictionary(字典)、Set(集合)。
可以使用type()函数判断类型,此外还有 isinstance来判断,isinstance 和 type 的区别在于:
type()不会认为子类是一种父类类型。
isinstance()会认为子类是一种父类类型。
4.列表和元组
列表可以完成大多数集合类的数据结构实现。列表中元素的类型可以不相同,它支持数字,字符串甚至可以包含列表(所谓嵌套)。
列表是写在方括号 [] 之间、用逗号分隔开的元素列表。
和字符串一样,列表同样可以被索引和截取,列表被截取后返回一个包含所需元素的新列表。
元组(tuple)与列表类似,不同之处在于元组的元素不能修改。元组写在小括号 () 里,元素之间用逗号隔开。
与Python字符串不一样的是,列表中的元素是可以改变的:
实例操作:
list1 = [1,2,3,4,5]
list1[0] = 9 #修改第一个位置
list1[1:3] = [10,11] #修改第二个位置到第三个位置元素
print(list1)
list1[1:3] = [] #元素设置为[]
print(list1)
输出
[9, 10, 11, 4, 5]
[9, 4, 5]