python的字符串、集合、for循环、异常等基础语法

#!/usr/bin/python

// 打印输出变量的2种方式
name='zhangsan'
print "badou hadoop study!,your name is %s" %(name)
print "you name is ", name

// 定义函数
def print_your_name(name):
print "your name is" , name
return ""

print print_your_name('zhangsan')
print print_your_name('lisi')

// python的3中集合
# python: hashmap -> dict -> {}
# python: array -> list -> []
# python: set -> set -> set()

# dict
color = {"red":0.2, "green":0.4, "blue":0.4}
print color["red"]
print color["green"]

# list
color_list = ['red','blue','green','yellow']
print color_list[2]

#set 可去重
a_set = set()
a_set.add('111')
a_set.add('222')
a_set.add('333')
a_set.add('111')


// 判断语句
a=1
if a > 0:
print 'a gt 0'
elif a == 0:
print 'a eq 0'
else:
print 'a lt 0'

// for list数组
a_list = []
a_list.append('111')
a_list.append('333')
a_list.append('555')
a_list.append('222')
a_list.append('444')

for value in a_list:
print value

// for dict(map) 无序
b_dict = {}
b_dict['aaa'] = 1
b_dict['bbb'] = 2
b_dict['ccc'] = 3
b_dict['ddd'] = 4
b_dict['eee'] = 5

for key,value in b_dict.items():
print key + ":" + str(value)


// for set 无序
c_set = set()
c_set.add('a')
c_set.add('b')
c_set.add('c')
c_set.add('d')
c_set.add('e')

for value in c_set:
print value


// 数字累加
sum = 0
for value in range(1,11):
sum += value
print sum

// while
cnt =2
while cnt > 0:
print 'love python'
cnt -= 1

// print dual
i =1
while i < 10:
i += 1
if i%2 > 0:
continue
print i


// 字符串长度
str = 'abcdefg'
print len(str)
// 字符串截取
print str[2:5]

// 字符串大写转小写
str = 'ABCDEF'
print str.lower()


// 抛异常
try:
a = 6
b = a/0
except Exception,e:
print Exception, ":",e

// IO异常
try:
fh = open('testfile','r')
except IOError, e:
print e
else:
print 'ok'
fh.close()

// math
import math
// 2的3次方
print math.pow(2,3)
// 浮点数
print math.floor(4.9)
// 四舍五入
print round(4.9)

import random
// 输出 数组无序
items = [1,2,3,4,5,6]
random.shuffle(items)
print items
// 输出一个随机数
a = random.randint(0,3)
print a

// 随机抽取指定个数
s_list = random.sample('abcdefg',3)
print s_list

群交流(262200309)
原文地址:https://www.cnblogs.com/webster1/p/7471792.html