计算字符串长度
s="abc"
result=0
for i in s:
result+=1
print(result)
使用函数
def count_letters(s):
"""此函数主要用于统计字符串个数"""
result=0
for i in s:
result+=1
return result #返回结果
=================
>>> def count_letters(s):
... result=0
... for i in s:
... result+=1
... return result
...
>>> count_letters("12334")
5
>>> count_letters("wdwq13323321")
12
>>>
小练习:写一个函数,能够计算一个列表的数字类型的总和
["1",2,3]=5 ["a","b"]=0
def count_sum_in_list(L):
if not isinstance(L,list):
return 0 #return被执行的话,那么函数后面的所有代码都不背执行了
result=0
for i in L:
if isinstance(i,(int,float)):
result+=i
return result
=================
>>> count_sum_list(10)
0
>>> count_sum_list([])
0
>>> count_sum_list([1,2,3,"a"])
函数的内部,一定要判断传入的参数类型是否是期望的类型,想清楚怎么容错,如果是,再继续计算
没有参数的函数
>>> def a():
... print("*"*10)
...
>>> a()
**********
>>> def a():
... for i in range(10):
... print("*"*i)
...
>>> a()
*
**
***
****
*****
******
*******
********
*********
import random
def five_rangdom_letters():
result=" "
for i in range(5):
result+=chr(random.randint(97,122))
return result
=======
import random
def random_letters(n):
if not isinstance(n,int):
return ""
result=" "
for i in range(n):
result+=chr(random.randint(97,122))
return result
random_letters(10)
小练习
random_letters(n,type) type参数可以是lower 也可以是upper,其他:返回“”
import random
def random_letters(n,type):
if not isinstance(n,int):
return " "
result=" "
if not (type=="lower" or type=="upper"):
return " "
result=" "
for i in range(n):
if type=="lower":
result+=chr(random.randint(97,122))
else:
result+=chr(random.randint(65,90))
return result
random_letter(10,"upper")
>>> def a():pass
...
>>> print(a)
<function a at 0x000001AA2F769A60>
>>> print(a())
None
>>> def get_values():
... return 1,2,3,4,5
...
>>> print(get_values)
<function get_values at 0x000002E1119E1E18>
>>> print(get_values())
(1, 2, 3, 4, 5)
>>> for i in get_values():
... print(i)
...
1
2
3
4
5
>>>
>>> def get_values():
... result=[ ]
... for i in range(5):
... result.append(i)
... return result
...
>>> print(get_values())
[0, 1, 2, 3, 4]
>>>
def a():
x=10
print(x)
a()
>>> x=100
>>> def a():
... x=1
... print(x)
...
>>> a()
1
>>> x
100
>>>
>>> x=456
>>> def a():
... global x
... x=123
... return x
...
>>> print(a())
123
>>>