用Python进行数据分析 第2章 Python的基础

2021-06-03  本文已影响0人  Jason数据分析生信教室

1. None

None是[什么都没有],也可以用来赋值

In [42]: a = None
In [43]: a is None
Out[43]: True
In [44]: b = 5
In [45]: b is not None
Out[45]: True

也可以在编写程序中,把None当作一个默认值。

def add_and_maybe_multiply(a,b,c=None):
    result = a + b 
    
    if c is not None:
        result = result * c
        
    return result 
In [54]: add_and_maybe_multiply(1,2,3)
Out[54]: 9

其实只要记住None是一个Type就行

In [56]: type(None)
Out[56]: NoneType

2. 控制循环

2.1 if和elif, else

if x < 0: 
    print('It\'s negative')    
x = -1

In [60]: runcell(20, '/Users/jason/.spyder-py3/temp.py')
It's negative
if x < 0 :
    print('It\s' negative')
elif x==0 :
    print('Equal to zero')
elif 0 < x < 5 :
    print('Positive but smaller than 5')
else :
    print('Positive and larger than or equal to 5')

3. for loop

求和,遇到None的时候跳过。

sequence = [1, 2, None, 4, None, 5]
total = 0
for value in sequence:
    if value is None:
        continue
    total += value 
   
   return total

4. while loop

在设定的条件变成FALSE之前一直重复,又或者可以在loop里面指明break的条件。

x=256
total=0
while x>0:
    if total > 500:
        break
    total += x
    x=x//2
print(x)

5. pass

if x<0:
    print("ngative")
elif x==0:
    pass
else:
    print("positive")

6. range

range(10)range(0,10)是一个概念
list(range(10))

list(range(10))
Out[8]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list(range(10))
Out[8]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

list(range(5,0,-1))
Out[9]: [5, 4, 3, 2, 1]

for loop 和 if 的组合

sum = 0
for i in range(10000):
    if i % 3==0 or i % 5==0:
        sum+=i
print(sum)
上一篇下一篇

猜你喜欢

热点阅读