1.编码问题
默认情况下,Python 3源码文件以 UTF-8 编码,所有字符串都是 unicode 字符串。 也可以为源码文件指定不同的编码,在文件头部加上:
#coding=gbk
2.关键字
保留字即关键字,Python的标准库提供了一个keyWordmodule,可以输出当前版本的所有关键字:
>>>importkeyword>>>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','return','try','while','with','yield']
3.注释
Python中单行注释以#开头,多行注释用三个单引号(''')或者三个双引号(""")将注释括起来。
4.变量
Python中的变量不需要声明。每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建
Python 3支持int、float、bool、complex(复数)。
数值运算:
Python可以同时为多个变量赋值,如a, b = 1, 2。一个变量可以通过赋值指向不同类型的对象。数值的除法(/)总是返回一个浮点数,要获取整数使用//操作符。在混合计算时,Python会把整型转换成为浮点数。
字符串:
python中的字符串str用单引号(' ')或双引号(" ")括起来,同时使用反斜杠(\)转义特殊字符
字符串可以使用 + 运算符串连接在一起,或者用 * 运算符重复
1text ='ice'+'cream'2PRint(text)34text ='ice cream'*35print(text)
使用三引号('''...'''或"""...""")可以指定一个多行字符串
1text ='''啦啦啦2喔呵呵呵呵3呵呵你妹'''4print(text)5text ='ice\6cream'7print(text)
如果不想让反斜杠发生转义,可以在字符串前面添加一个 r 或 R,表示原始字符串。
如 r"this is a line with \n" 则\n会显示,并不是换行
1text1 = r'E:\notice'2text2 ="let's go!"3text3 = r'this is a line with \n'4print(text1)#E:\notice5print(text2)#let's go!6print(text3)#this is a line with \n
字符串有两种索引方式,第一种是从左往右,从0开始依次增加;第二种是从右往左,从-1开始依次减少。
python中没有单独的字符类型,一个字符就是长度为1的字符串
1text ='ice cream'2print(len(text))34print(text[0])#i5print(text[-9])#i67print(text[8])#m8print(text[-1])#m
python字符串不能被改变。向一个索引位置赋值会导致错误
1text ='ice cream'2text[0] ='t'#报错3print(text)
还可以对字符串进行切片,获取一段子串。用冒号分隔两个索引,形式为变量[头下标:尾下标]。
截取的范围是前闭后开的,并且两个索引都可以省略:
1text ='ice cream'2print(text[:3])#ice3print(text[4:9])#cream4print(text[4:])#cream
5.三目运算符
1x = 1002y = 2003z = xifx > yelsey4print(z)#200
6.分支
if-else 语句与其他语言类似,不再赘述
if-elif-else 语句,相当于c或java语言中的if-else if-else :
1whileTrue:2score = int(input("Please input your score :"))3if90 <= score <= 100:4print('A')5elifscore >= 80:6print('B')7elifscore >= 70:8print('C')9elifscore >= 60:10print('D')11else:12print('Your score is too low')
7.循环
while循环语句一般形式:
while判断条件:
statements
1importrandom23print("hello world!\n")4number = random.randint(1, 10)5temp = input("Please input a number :")6i =int(temp)78whilei !=number:9print("wrong...")10ifi <number:11print("required a bigger number")12else:13print("required a smaller number")14temp = input("Please input a number :")15i =int(temp)1617print("yes...")
for循环的一般格式如下:
for<variable>in<sequence>:
<statements>
else:
<statements>
1languaegs = ['C','c++','java','python']2forlanguageinlanguaegs:3print(language, len(language))
循环语句可以有else子句
它在穷尽列表(以for循环)或条件变为假(以while循环)循环终止时被执行
但循环被break终止时不执行.如下查寻质数的循环例子
1fornuminrange(2, 10):2forxinrange(2, num):3ifnum%x ==0:4print(num,'equals', x,'*', num//x)5
break6else:7#循环中没有找到元素8print(num,'is a prime number')
如果需要遍历数字序列,可以使用内置range()函数:
1#range()函数,含头不含尾2#0~43foriinrange(5):4print(i)56#2~77foriinrange(2, 8):8print(i)910#1~9 步长为311foriinrange(1, 10, 3):12print(i)
range()函数与for循环结合:
1languaegs = ['c','c++','java','python']2foriinrange(len(languaegs)):3print(i,':', languaegs[i])