Byte of Python学习笔记二


四. 基础知识
字面常量: 'a string', "It's a string", 4, 1.23
数值,三种类型:
1. 整型 2 (不分int和long)
2. 浮点型 52.3E-4, 2.25
3. 复数 (-5+4j)
字符串,默认unicode编码,三种表示方式:
1. 单引号 'string'
2. 双引号 "string" 与'string'等同
3. 三重引号 '''this is a string''' 或 """this is a string"""
注意:三重引号可以引多行,如
'''This is a multi-line, this is the first line.
   This is the second line.
   "what's your name".
 '''
转义字符:\n, \t, \'等

行尾单独的\为续行符,连接多行,如
"This is the first line. \
  This is the second line."
等价于
"This is the first line. This is the second line."

原生字符串:在字符串前加前缀r或R,使字符串中的特殊字符保持原貌。如
>>>print(r"abc\ndef")
abc\ndef
>>>print("abc\ndef")
abc
def

字符串不可变,即定义好的字符串不能修改

字符串连接:将两个字符串放到一起,它们自动连接起来
>>>print('abc1' 'def')
abc1def

format方法:Python字符串都有format方法
>>>"{0} is {1} years old".format("Li", 20)
'Li is 20 years old'
>>>'{0} is {1:.3}'.format('s', 1/3)
's is 0.333' #{1:.3}保留3位有效数字
>>>'{name} wrote {book}'.format(name='I', book='abc')
'I wrote abc'
深入阅读:http://www.python.org/dev/peps/pep-3101/

标识符(变量名等)命名规则:
1. 首字符必须为字符(unicode字符或ASCII字符)或下划线
2. 其余字符为字符(unicode字符或ASCII字符),下划线或数字
3. 区分大小写

基本数据类型:数字和字符串

Python中所有东西皆为对象,包括数字,字符串和函数

tips: IDLE使用技巧
File->New Window, 在新打开窗口中编写python文件,然后保存。
F5或Run->Run Module执行Python文件

变量直接赋值,使用;不需要声明数据类型

行尾分号(;)可有可无,当一行有多个语句时必须要分号(;)

Python通过行的缩进来区分语句组,即块,而不是通过花括号,同一块中的语句,缩进都一样。

五. 操作符和表达式
特殊操作符:
* 乘法 1 * 4 = 4, 'abc' * 3 = 'abcabcabc'
** 幂运算 2**3=8
// 相除向下求整 4//3=1,-4//3=-2
% 模运算,操作数可以是浮点数,等价于 a%b=a - (a//b)*b
~ ~x=-(x+1) ~5=-6

六. 控制流
1. if 语句
if-elif-else,elif和else可选。如
guess=1
if guess==1:
     print('a')
elif guess==2:
     print('b')
else: www.2cto.com
     print('c')

2. while语句
while-else,else可选。如
running = True
while running:
     #doSomething
else:
     #doSomething else

3. for语句
for-else,else可选。如
for i in range(1,5):
     print(i)
else:
     print('The for loop is over')

4. break
跳出while和for循环
 
5. continue
跳过while和for本次循环

摘自:蓝猫的专栏

相关内容

    暂无相关文章

评论关闭