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

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

你可能感兴趣的:(python 教程笔记day2)