1.for
#逐个取数
a=['d','d']
b=''
for x in a:
b+=x
print(b)
2.range
>>> a=[range(5)]
>>> a
[range(0, 5)]
>>> print(a)
[range(0, 5)]
>>> list(range(5))
[0, 1, 2, 3, 4]
>>> list(range(1,5))
[1, 2, 3, 4]
>>> list(range(1,5,2))
[1, 3]
>>> list(range(2,30,10))
[2, 12, 22]
a=list(range(2,30,10))
b=0
for x in a:
b+=x
print(b)
3.while
n=1
s=0
while n<10:
s+=n
n+=1
print("s:",s,"n:",n)
print(n)
?
break:
n=1
s=0
while True:
s+=n
n+=1
print("s:",s,"n:",n)
if s>30:
break
print(n)
?
?continue:满足条件直接进行下一个循环
n=1
s=0
while True:
s+=n
print("s:",s,"n:",n)
if s<10:
continue
if s>20:
break
n += 1
print(n)
?4.内置函数
Python 内置函数 | 菜鸟教程 (runoob.com)
>>> a=max
>>> a([1,4,7])
7
>>>
?5.自定义函数
def mm_c(a,b):
if a>b:
return a
else:
return b
if __name__=='__main__': #相当于C语言中int main()
c=mm_c(3,7)
print(c)
注:python中可以返回多个值,例如:
return a,b
def mm(a,b=0) #b=0为默认,当输入为一个数时
?一个小坑:
def add_h(a=[]):
a.append('add')
return a
c=add_h([1,2,3])
print("c:",c)
c=add_h()
print("c2:",c)
c=add_h()
print("c3:",c)
?所以尽量不用可变量作为参数
可以传入任意个数的参数? ? ? ? 用*表示? ? ? ?
def sum_a(*num):
sum=0
for i in num:
sum+=i
return sum
if __name__=='__main__':
a=sum_a(1,3)
b=sum_a(1,3,5)
c=sum_a(7,7,7,7)
print("a:",a,"\nb:",b,"\nc:",c)
?
|