python 教程笔记day2

#Fibonacci series:
# the sum of two elements defines the next
a, b = 0, 1
while b < 10:
    print(b)
    a, b = b, a+b
    
1
1
2
3
5
8


a,b =0,1
while b < 1000:
    print(b, end=',')
    a, b = b, a+b

  1. More Control Flow Tools
    4.1 if statements
x = int(input("Please enter an integer:"))
Please enter an integer:>? 42
if x < 0:
    x = 0
    print('Negative changed to zero')
elif x == 0:
    print('Zero')
elif x == 1:
    print('Single')
else:
    print('More')
   

4.2 for statements

#Measure some strings:
words = ['cat', 'window', 'defenestrate']
for w in words:
    print(w,len(w))
    
cat 3
window 6
defenestrate 12

for w in words[:]: #Loop over a slice copy of the entire list
    if len(w) > 6:
        words.insert(0,w)
        
words
['defenestrate', 'cat', 'window', 'defenestrate']

4.3. The range() Function

a = ['Marry','had','a','little','lamb']
for i in range(len(a)):
    print(i,a[i])
    
0 Marry
1 had
2 a
3 little
4 lamb

a = ['Marry','had','a','little','lamb']
for i in range(len(a)):
    print(i,a[i])
    
0 Marry
1 had
2 a
3 little
4 lamb
print(range(10))
range(0, 10)
list(range(5))
[0, 1, 2, 3, 4]

4.4 break and continue Statements, and else Clauses on Loops

for n in range(2,10):
    for x in range(2,n):
        if n % x == 0:
            print(n, 'equals', x, '*', n//x)
            break
        else:
            #loop fell through without finding a factor
            print(n,'is a prime number')

for num in range(2,10):
    if num % 2 == 0:
        print("Found an even number",num)
        continue
    print("Found a number",num)
    
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9

4.5 pass Statements

空类

class MyEmptyClass:
    pass

4.6 Defining Functions

def fib(n): # write Fibonacci series up to n
    """Print a Fibonacci series up to n."""
    a,b = 0,1
    while a < n:
        print(a,end=' ')
        a,b = b, a+b
    print()
    
fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 
fib
<function fib at 0x03617B28>
f = fib
f(200)
0 1 1 2 3 5 8 13 21 34 55 89 144 

https://docs.python.org/3/tutorial/controlflow.html

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 太阳是爸爸, 月亮是妈妈, 星星是孩子。 太阳白天上班, 月亮晚上守夜, 星星一个人在家好孤单。 星星想通过自己的...
    金赛月阅读 3,816评论 0 5
  • 习惯了不该习惯的习惯,却执着着不该执着的执着。有时候,在乎得太多,对自己而言也是一种折磨。 ​ ​​​
    釉芷阅读 891评论 0 1
  • 买房,如何证明他就是业主?怎么分辨真假房本,揭穿这种万恶的假房本? 中亿行小编教你简单10招,帮您验明真假房产证。...
    中亿行阅读 7,890评论 0 0
  • 半夜起床上厕所,困的人神共愤。回来重新躺在床上,感受到他也醒了一下,好像每次我翻个身或者上个厕所都会惊醒他,往他臂...
    叙理的猫阅读 1,508评论 0 0

友情链接更多精彩内容