hug2wisdom / learnpython

note the points of learn python
0 stars 0 forks source link

prime numbers & Fibonacci series #6

Open hug2wisdom opened 4 years ago

hug2wisdom commented 4 years ago
for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print(n, 'equals', x, '*', n // x)
            break
    else:
        print(n, 'is a prime number')

(Yes, this is the correct code. Look closely: the else clause belongs to thefor loop, not the ifstatement.)

else 不仅仅可以与 if 连在一起使用,还可以与 fortrywhile 使用。

hug2wisdom commented 4 years ago

list(range(10, 10)), 返回的是 []

hug2wisdom commented 4 years ago

Fibonacci series

def fib(n): # write Fibonzcci 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)
# result
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597