Python学习笔记-第二天

学习了Python的数据类型和变量
字符串的编码
常用数据结构:list/tuple dict/set
条件判断和循环

** foreach **
names = ['chen', 'li', 'jiang']
# foreach
for name in names:
    print name

# for x in ...
sum = 0
for x in [1, 2, 3, 4, 5, 6, 7]:
    sum = sum + x
print sum

# range
print range(5)
sum = 0
for x in range(8):
    sum = sum + x
print sum

# while loop
sum = 0
n = 8
while n > 0:
    sum = sum + 2
    n = n - 2
print sum

# raw_input()--字符串
# int()--数字
** if **
a = 100
if a < 10:
    print 'aaa'
elif a < 20:
    print 'bbb'
else:
    print 'ccc'

if a:
    print a
** dict **
#!/usr/bin/env python
# -*- coding: utf-8 -*-

name_score = {'chen': 97, 'li': 0, 'jiang': 90}
# 打印元素
print name_score['chen']

# 元素重新赋值
name_score['chen'] = 34
print name_score['chen']

# 判断元素是否存在
print 'wen' in name_score

# 指定返回值
print name_score.get('wen', 55)
** list **
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# 可变数组
a = ['c', 'a', 'b']

# 访问元素
print a[0]
print a[-1]

# 长度
print len(a)

# 追加元素
a.append('d')
print a

# 指定位置追加元素
a.insert(0, 'e')
print a

# 删除元素
a.pop()
print a

# 根据索引删除元素
print a.pop(1)

# 替换值
a[0] = 'i'
print a

# 排序
a.sort()
print a

# list 嵌套 list
nerd_list = ['a', 'b', [1, 2], 3]
print nerd_list[2]
print nerd_list[2][0]
print nerd_list
** set **
#!/usr/bin/env python
# -*- coding: utf-8 -*-

nums = set([1, 2, 3, 1])
print nums

# add key
nums.add(5)
nums.add(5)
print nums

# remove key
nums.remove(1)
print nums

nums1 = set([6, 1])
# 求交集
print nums & nums1
# 求并集
print nums | nums1
** tuple **
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# tuple为不可变的数组
classmates = ('chen', 'li', 'jiang')
print classmates

# empty tuple
t = ()
print t

# one element tuple
t = (1,)
print t

# 错误的单元素tuple
t = (1)
print t

# 可变的tuple
t = ('a', 'b', ['A', 'B'])
print t[2][0]
t[2][0] = 'C'
print t

你可能感兴趣的:(Python学习笔记-第二天)