CS61A Python---Bool/if/循环

Boolean value : True / False

and

or

not

 

if 语句

if <condition>:
    <statement>
    <statement>


-------
if <condition>:
<statement>
elif <condition>:
  <statement>
else :
   <statement>

 e.g

质数检验

def is_prime(n):
    """Return True iff N is prime.
    >>> is_prime(1)
    False
    >>> is_prime(2)
    True
    >>> is_prime(8)
    False
    >>> is_prime(21)
    False
    >>> is_prime(23)
    True
    """
    return n > 1 and smallest_factor(n) == n

def smallest_factor(n):
    """Returns the smallest value k>1 that evenly divides N."""
    x = 2
    while x * x <= n :
        if n % x == 0 :
            return x
        x += 1
    return n
    pass

def print_factors(n):
    x = 2
    while n != 1 :
        if(n % x == 0) :
            n/=x
            print (x)
        else :
            x += 1
    """Print the prime factors of N.
    >>> print_factors(180)
    2
    2
    3
    3
    5
    """
    pass

 

 

while循环

while <condition>:
    <statement>
    <statement>

 

posted @ 2022-02-24 19:57  liankewei123456  阅读(22)  评论(0编辑  收藏  举报