python你好代码-Python学习代码——基础篇

#1.打印

print("你好 世界")#2.列表(java中的数组)

name = ["lll", "gx", "zj", "xx"]print(name[-2])#3. if判断

xmTail = 1.75xmWight= 80.5BMI= xmWight / (xmTail *xmTail)print(BMI)if BMI < 18.5:print("小明过轻")elif BMI >= 18.5 and BMI < 25:print("小明正常")elif BMI >= 25 and BMI < 28:print("小明过重")elif BMI >= 28 and BMI < 32:print("小明肥胖")else:print("小明严重肥胖")#4. for循环

names = ["xiaoli", "dali", "li", "guan"]for name innames:print(name)

numbers= [1, 2, 3, 4, 5]#range(5)函数是生产序列数方法

for number in range(5):print(number)#python中的dict 类似java中的map

dict = {'Michael': "kjksd", 'Bob': "kkkk", 'Tracy': "ooxx"}print(dict['Michael'])#判断可以是否存在

print('Thomas' indict)#如果jjk不存在返回None

print(dict.get("jjk"))#删除dict中的值

dict.pop('Bob')print(dict)#5. set 类似于数组无序 不重复

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

s.add("s")print(s)

s.remove("s")print(s)

s1= set([1, 2, 3])

s2= set([2, 3, 4])print("s1取交集")print(s1 &s2)print("s1取并集")print(s1 |s2)#6. 简单常用函数#取绝对值

print(abs(-1.23))print(abs(1.23))#取最大值

print(max(1, 2, 3, 4, 5, 8))

arr= [1, 2, 3, 4, 4, 5]print(max(arr))#取最小值

print(min(1, 2, 3, 4, 5, 8))

arr= [1, 2, 3, 4, 4, 5]print(min(arr))#类型转换

print(int('123'))print(int(12.34))print(float('12.34'))print(str(1.23))print(str(100))print(bool(1))print(hex(23))#7. 函数的定义和调用

from _ast importNumdefsum_seris(x):

sum=0for number inrange(x):print(number)

sum= sum +numberreturnsum#调用函数

print(sum_seris(10))#不做任何处理用pass

defTest_number(x):

s=0if x == 5:

s= 100

elif x == 10:

s= 1000

else:pass

returnsprint(Test_number(11))#参数检查

defTest_number1(x):if notisinstance(x, (int, float)):raise TypeError('参数类型不对')

s=0if x == 5:

s= 100

elif x == 10:

s= 1000

else:pass

returnsprint(Test_number1(11))#python可以有多个返回值

#默认返回值

def infor(name, gender, age=7, city="wuhan"):print('name:', name)print('gender:', gender)print('age:', age)print('city:', city)print(infor("lll", "n"))print(infor("zj", "w", 6))print(infor("gx", "w", 6, 'hefei'))#传递list参数

defcalc(numbers):

sum=0for n innumbers:

sum= sum + n *nreturnsumprint(calc([1, 2, 3]))print(calc([1, 2, 3, 7, 9]))#传递可变参数

def calcs(*numbers):

sum=0for n innumbers:

sum= sum + n *nreturnsumprint(calcs(1, 2, 3))print(calcs())#8. python 中的切片操作符slice

L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']print(L[0:3])print(L[:3])print(L[0:])

LL= L = list(range(100))print(LL[:10:2]) #前10个数,每两个取一个

print(LL[::5]) #取所有,每五个取一个

#列表生成式代替循环

print([x * x for x in range(1, 11)])#for循环后面还可以加上if判断 仅偶数的平方

print([x * x for x in range(1, 11) if x % 2 ==0])#双重循环

print([m + n for m in 'ABC' for n in 'XYZ'])#9. 用isdigit函数判断是否数字#判断是否为数字或者字母

str_1 = "123"str_2= "Abc"str_3= "123Abc"

print(str_1.isdigit())#用isalpha判断是否字母

print(str_1.isalpha())#isalnum判断是否数字和字母的组合

print(str_1.isalpha())#生成器

g = (x * x for x in range(10))print(next(g))#map()传入的第一个参数是f,即函数对象本身。#由于结果r是一个Iterator,Iterator是惰性序列,#因此通过list()函数让它把整个序列都计算出来并返回一个list。

from _functools importreducedeff(x):return x +x

r= map(f, [1, 2, 3])print(list(r))#10. reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,#这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算

defadd(x, y):return x +yprint(reduce(add, [1, 3, 5, 7]))#练习把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字

defreturnName(Str):

rStr= ''

for n, x in enumerate(Str, 1):if x.islower() and n == 1:

x=x.upper()elif x.isupper() and n != 1:

x=x.lower();

rStr= rStr +xreturnrStrprint(returnName("admin"))print(list(map(returnName, ['adam', 'LISA', 'barT'])))#upper() :将字符串转成大写,并返回一个拷贝#lower() :将字符串转成小写,并返回一个拷贝#capitalize() :将字符串首字母,并返回一个拷贝#title() :将每个单词的首字母大写,并返回一个拷贝#isupper() :判断一个字符串是否是大写#islower() :判断一个字符串是否是小写

#filter()也接收一个函数和一个序列。和map()不同的是,filter()把传入的函数依次作用于每个元素#,然后根据返回值是True还是False决定保留还是丢弃该元素。

defis_odd(n):return n % 2 == 1

print(list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])))print(list(map(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])))#11. Python内置的sorted()函数就可以对list进行排序

print(sorted([36, 5, -12, 9, -21]))#绝对值大小排序

print(sorted([36, 5, -12, 9, -21], key=abs))#倒序排列

print(sorted([36, 5, -12, 9, -21], reverse=True))#字母排序可实现忽略大小写的排序

print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower))#12. 关键字lambda表示匿名函数,冒号前面的x表示函数参数

print(list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])))#13. 装饰器

deflog(func):def wrapper(*args, **kw):print('call %s():' % func.__name__)return func(*args, **kw)returnwrapper

@logdefnow():print('2015-3-25')print(now())#偏函数 进制转换

def int2(x, base=2):returnint(x, base)print(int2('1010101'))#14. 字典类型:映射即字典{"哈希值":"对象"}

dict ={}print(type(dict))

dict1= {'x': 1, 'y': 2}print(dict1)#遍历字典并打印出来

for xx indict1.keys():print('dict include %s is %d' %(xx, dict1[xx]))#15. 推导式#列表推导式:简化代码变量(有点类似于java中的三目运算符)

alist =[]for i in range(1, 11):if (i % 2 ==0):

alist.append(i*i)print(alist)#用推导式完成上述代码

blist = [i * i for i in range(1, 11) if (i % 2) ==0]print(blist)#字典推导式

num ={}for i indict1:

num[i]=0print(num)#用推导式完成上述代码

num = {i: 0 for i indict1}print(num)

你可能感兴趣的:(python你好代码-Python学习代码——基础篇)