无参数版本,无返回值
这是自己定义的函数,实现打印hello world 1000遍
()里面的是参数,参数可以有可以没有,主要看下面的函数需不需要参数
不能起名内置函数同名
def print_hello():
i=0
while i<1000:
print('hello world')
i+=1
print_hello()
有参数版本,无返回值
def print_hello(a):#参数版本,无返回值
i=0
while i<a:
print('hello world')
i+=1
print_hello(10)
列表与字典
list1=['name','age','gender']
list2=['laowang',19,'boy']
#第一种
dict1={}
for i in range(len(list1)):
dict1[list1[i]]=list2[i]
print(dict1)
#第二种
ret=dict(zip(list1,list2))
print(ret)
#第三种
new_dict={list1[i]:list2[i] for i in range(3)}
print(new_dict)
列表推导式
#第一种
list1=[2,4,6,8,10,12,14,16,18,20]
#第二种 利用range
#ret1=list(range(21))
ret1=list(range(2,21,2))
# range(i, j) producesi, i + 1, i + 2, ..., j - 1.
print(ret1)
#第三种
num_list=[]
i=1
while i<21:
if i%2==0:
num_list.append(i)
i+=1
print(num_list)
#第四种
num_list2=[]
for j in range(1,21):
if j%2==0:
num_list2.append(j)
print('num_list2=',num_list2)
#第五种
num_list3=[obj for obj in range(1,21) if obj%2==0]
print('num_list3=',num_list3)
判断数据类型
print(isinstance(list_new2,int))
isinstance 判断类型用的 前面写对象,后面写类型
list_new2=[[1,2,3],'abc',1,3,5,7,2.3,[2,3,4]]
for obj in list_new2:
if isinstance(obj,list):
for i in obj:
print(i)
elif isinstance(obj,int):
print(obj)
elif isinstance(obj,float):
print(obj)
else:
pass
enumerate 前面对应的是索引,后面的对用的是值
枚举函数
ret1=enumerate(list_new2)
print(ret1)
for k in ret1:
print(k)
字符串与列表相互转换
str_new='hello world'
# str_to_list=list(str_new)
print(str_new.split())
list_new=['hello','world','!']
str1=''
for i in list_new:
str1+=i
print(str1)
#第二种方法
str2=''.join(list_new)
print(str2)
#推导式实现
str3=''.join([str(k) for k in list_new])
print(str3)