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 @   liankewei123456  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示