基础
print("hello world")#注意到print这是一个函数
help('len')
help('return')
代码会告诉你怎么做,注释会告诉你为何如此。
字面常量
常量,值不能改变
5
1.23
This is a string #文本
数字
- 整数 (integers)
- 浮点数 (floats)
int类型可以指任何大小的整数
3
3.23
52.3E-4 # 52. 3 * 10^(-4)
字符串
A string is a sequence of characters.
- 单引号
- 双引号
- 三引号
格式化方法
age=20
name = 'Swaroop'
print('{} was {} years pld when he wrote this book'.format(name,age))
print('Why is {} playing with that python?'.format(name))
输出
Swaroop was 20 years pld when he wrote this book
Why is Swaroop playing with that python?
python中 format 放大所做的事情便是讲每个参数替换至格式所在的位置。
#对于浮点数'0.333'保留小数点后三位
print('{0:.3f}'.format(1.0/3))
# 使用下划线填充文本,并保持文字处于中间位置
# 使用(^)定义'___hello___'字符串长度为11
print('{0:^11}'.format('hello'))
#给予关键词输出'Swaroop wrote A Byte of Python'
print('{name} wrote {book}'.format(name='Sawaroop',book='A Byte of Python'))
输出
0.333
hello
Sawaroop wrote A Byte of Python
注意print总会以一个不可见的“新一行”字符(\n)结尾,可以通过end指定其应以空白结尾
print('a',end=' ')
print('b',end=' ')
print('c')
a b c
转义序列
#转移字符
print('What\'s your name?') #单引号
print("what\'s your name?") #双引号
print('This is the fisrt line\nThis is the second line')
print(r'Newlines are indicated by \n')
i=5
print(i)
i=i+1
print(i)
s='This is a multi-line string.\
This is the second line.'
print(s)
i=\
5
print(i)
输出
What's your name?
what's your name?
This is the fisrt line
This is the second line
Newlines are indicated by \n
5
6
This is a multi-line string.This is the second line.
5
变量
标识符命名
同c,c++。侧重自身理解,毕竟有时候明明是给自己使用的。
数据类型
基本类型:数字和字符串
对象
python讲程序中的任何内容统称为对象(Object)。
python是强面向对象的,所有一切都是对象,包数字、字符串与函数。
i=5
print(i)
i=i+1
print(i)
s='This is a multi-line string.\
This is the second line.'
print(s)
5
6
This is a multi-line string.This is the second line.
逻辑行与物理行
对每一个物理行最多只写如一行逻辑行
缩进
不正确的缩进会导致错误。缩进很重要,if while for循环均靠缩进来分辨是否属于循环里面