Python3.5初学笔记

之前学过C,C#,Java等课程,惊叹于python的简约。【笑】
刚开始学,做点笔记吧。
由于python3.0之后终于默认采用了Unicode编码,所以为了避免乱码问题,先在编译器把编码设为UTF-8,在每个.py开头加上
参考教程来自“廖雪峰的官方网站”http://www.liaoxuefeng.com/

# -*- coding:utf-8 -*-

python为动态语言,大小写敏感,不需要指定变量数据类型,整形数据无限制大小,“”‘’表示的都是字符串。

a = 123 # a是整数
print(a)
a = 'ABC' # a变为字符串
print(a)

r’\\\’,使用r’ ‘可以忽略转义字符,使用”’…”’可以表示换行,与’\n’一样。如”’line1…
line2…line3”’。布尔值可以用and or not 运算。

if age >= 18:
    print('adult')
else:
    print('teenager')

空值为None。在python中,常量并不能得到保证,如 PI =3.14仍然是一个变量。str表示字符串类型,bytes类型用b 表示。如下编码解码。

>>> 'ABC'.encode('ascii')
b'ABC'
>>> '中文'.encode('utf-8')
b'\xe4\xb8\xad\xe6\x96\x87'
>>> '中文'.encode('ascii')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)

len()函数计算长度,如print(len(‘Hello world!’)),在非命令行下,输出要用print()。
格式化语句形式似于c语言。

print('I am %s',%(HB))
name = 'HB' 
print('I am %s',%(name))
n = input('Please input the animal!')
y = (int) input('Please input the age!')
print('There is a %s and it is %d years old',%(n,y))       

list 和 tuple
list 列表是一种有序数据类型,类似于数组。

names = ['HB','NN','CH']
//求个数
len(names)
//由指定索引得出
names[0]
//还可以倒数
names[-1],name[-2]等等,当然要注意下标越界。

list有insert(index,”),append(”),pop()/pop(index)即插入,追加,删除方法。list中数据类型可以不同,也可以是另一个list

 s = ['python', 'java', ['asp', 'php'], 'scheme']

tuple类似于list,不过tuple一经初始化便不能修改,尽量用tuple代替list,代码更安全。tuple自然没有insert等方法。

tuple = (1,2,3)
//空tuple
tuple = ()
//注意,定义一个元素的tuple时,要使用" , "避免歧义
tuple = (1,)
//注意,当tuple中有list时,list可变
tuple = (1,2,[4,5])
tuple[2][0] = 1
tuple[2][1] = 3

结果为 tuple = (1,2,[1,3])

猜你喜欢

转载自blog.csdn.net/sinat_33878878/article/details/69814578