python学习之基础知识练习

废话不多说,直接上代码。着实体现出了python的简洁特性。

#coding:utf-8
'''
Created on 2018年10月28日

@author: Administrator
'''
from types import InstanceType
#导入模块定义别名
from random import randint as getRand

#字符串转为int
age = int('6')
print type(age)
age = str(6)
print type(age)


#字符串长度,range返回的是一个集合
st = 'abc'
print len(st)
print range(len(st))
#开始的9到-9之间,步频是-4,结果为[10, 6, 2, -2, -6] 
print range(10,-10,-4)

#遍历st,并打印下标
for i in range(len(st)):
    print st[i] , '%f %d' %(i,i)

#文件操作,追加操作
content = '学习python'
#f = open('D:\\testFiles\\part1.txt', 'a')
#f.write(content)
#f.close()

#enumerate() 可以获取到所有的key,并通过对应的key获取到对应的值
ht = {'name':'bob'}
for i,key in enumerate(ht):
    print key,ht[key]
    
#type() 获取对象的类型
print type(ht)
print type(st)

#判断isinstance 判断是什么类型的
print isinstance(6 , int)
print isinstance(ht, dict)


#del 删除元素
aList = ['1','r',5]
print aList
del aList[1]
print aList

del ht['name']
print ht


#sort排序,
date = []
date.append({"name":"jack","grade":"500","has":3})
date.append({"name":"bob","grade":"500","has":2})
date.append({"name":"marry","grade":"700","has":1})
#gradez正序排列 has逆序排列
#{'grade': '500', 'has': 2, 'name': 'bob'}
#{'grade': '500', 'has': 3, 'name': 'jack'}
#{'grade': '700', 'has': 1, 'name': 'marry'}
date.sort(key=lambda z:(z["grade"],z["has"]), reverse=False)
for i in date:
    print i
#grade正序排列  has逆序排列 
#{'grade': '500', 'has': 3, 'name': 'jack'}
#{'grade': '500', 'has': 2, 'name': 'bob'}
#{'grade': '700', 'has': 1, 'name': 'marry'}   
date.sort(key=lambda z:(z["grade"],-z["has"]), reverse=False)
for i in date:
    print i


#对象比较  支持多个比较操作
print 3<4<5  # (3<4) and (4<5)
print 3<4==5 # (3<4) and (4==5)
print 3<4<5 !=7 >1 # 从左向右执行

#java中的collection.reverse(arrayList) 反转序列
bList = ['134','wqertqw','7','t']
print bList[::-1]
print bList[::-2] #步幅是2
print bList[0:1:2] #从什么位置开始:到哪一个位置结束:步幅是多大

#进行排序,正序
print sorted(bList)

# list   is   is not
#==判断的是数值(先计算再比较数值)   is比较的是指针
f1 = f2 = 4.3
print f1==f2
print f1 is f2

f1 = 4.3
f2 = f1
print f1==f2
print f1 is f2

f1 = 4.3; f2 = 3.3 + 1
print f1==f2
print f1 is f2  # false

#cmp  比较
print cmp('b', '1')
print cmp(2,12)
print cmp(6,6)


#round()进行四舍五入
print round(100.100)
print round(100.500)

#random 取随机数
print getRand(1,100)


#in 操作
print 'ac' in 'sgsab'

#导入string模块
import string
print string.capitalize("hello")  #首字母大写
print string.upper("help") #全部大写
print string.lower("OK") #全部小写
print string.split("afjoqwejowq qwerqojrq") #默认通过空格分割
print string.split("afjoqwejowq, qwerqojrq,a24305285", ",", 1) #指定分割符,并指定最大的分割个数 ['afjoqwejowq', ' qwerqojrq,a24305285']
#左去空格  右去空格  左右去空格
print string.lstrip("    a b")
print string.rstrip("    a b   ")
print string.strip("    a b   ")


#异常信息的捕获
try:
    float("adfa")
except Exception,e:
    print "float trans error:" , e
finally:
    print "done"
    
    
#传递函数
def myTest(num):
    return num * 2

def convers(func,seq):
    print "covert everyone in seq to same type"
    return [func(eachnum) for eachnum in seq]

mySeq = [132, 23.6,-6.2e8,999999L]
#面向函数编程,将函数传来传去
print convers(int, mySeq)
print convers(float, mySeq)
print convers(myTest, mySeq)


#参数默认赋值
def default(cost,rate=0.8):
    return cost * rate
print default(100) # 不传取默认值  传取传入的值
print default(100, 0.9) 

#一个*代表可以传递多个参数
def defaul(cost,rate=0.8, *theRest):
    for other in theRest:
        print other
        cost += other
    return cost * rate
print defaul(100, 0.9,80,345,66)  #这里有默认值的也一定要传


# 两个*代表可以传递键值对的参数
def defaul3(cost,rate=0.8, **theRest):
    for other in theRest.keys():
        print "key:",other
        cost += theRest[other]
    return cost * rate      

print defaul3(100, 0.7, name=66,price=77)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值