zoukankan      html  css  js  c++  java
  • 条件、循环及其他语句

    1.自定义分隔符:
    >>> print("I", "wish", "to", "register", "a", "complaint", sep="_",end='')      seq 默认为‘ ’end=' '
    I_wish_to_register_a_complaint

    2.用作布尔表达式(如用作if语句中的条件)时,下面的值都将被解释器视为假:

    False , None , 0,  " ", ( ) ,[ ] ,{ } 换而言之,标准值False和None、各种类型(包括浮点数、复数等)的数值0、空序列(如空字符串、空元组和空列表)以及空映射(如空字典)都被视为假,而其他各种值都被视为真,包括特殊值True。

    3.条件表达式:

    status = "friend" if name.endswith("Gumby") else "stranger" 

      如果为真 ,提供的第一个值'friend',否则则为假 ,提供后面一个值'stranger'

    4.短路逻辑和条件表达式

    name = input('Please enter your name: ') or '<unknown>' 

     如果input值为真则返回,否则返回后者

    5.while循环

    name = ''
    while not name.strip():
    name = input('Please enter your name: ')
    print('Hello, {}!'.format(name))

    6.for循环

    words = ['this', 'is', 'an', 'ex', 'parrot']
    for word in words:
    print(word)

    7.①迭代字典

    d = {'x': 1, 'y': 2, 'z': 3} 

    for key, value in d.items():
      print(key, 'corresponds to', value)

    8.并行迭代

    names = ['anne', 'beth', 'george', 'damon']
    ages = [12, 45, 32, 102]

    for i in range(len(names)):
      print(names[i], 'is', ages[i], 'years old')

    >>> list(zip(names, ages))
    [('anne', 12), ('beth', 45), ('george', 32), ('damon', 102)]

     ②迭代时获取索引

     

    index = 0
    for string in strings:
    if 'xxx' in string:
    strings[index] = '[censored]'
    index += 1

    for index, string in enumerate(strings):
    if 'xxx' in string:
    strings[index] = '[censored]'

    ③反向迭代和排序后再迭代

    >>> sorted([4, 3, 6, 8, 3])
    [3, 3, 4, 6, 8]
    >>> sorted('Hello, world!')
    [' ', '!', ',', 'H', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
    >>> list(reversed('Hello, world!'))
    ['!', 'd', 'l', 'r', 'o', 'w', ' ', ',', 'o', 'l', 'l', 'e', 'H']
    >>> ''.join(reversed('Hello, world!'))
    '!dlrow ,olleH'

     

     8.跳出循环

    break

    要结束(跳出)循环,可使用break。

    from math import sqrt
    for n in range(99, 0, -1):
      root = sqrt(n)
      if root == int(root):
        print(n)
        break

    ②continue

    语句continue没有break用得多。它结束当前迭代,并跳到下一次迭代开头。

    这基本上意味着跳过循环体中余下的语句,但不结束循环。这在循环体庞大而复杂,且存在多个要跳过它的原

    因时很有用。在这种情况下,可使用continue

     9.简单推导

    列表推导

    >>> [x*x for x in range(10) if x 3 == 0] %
    [0, 9, 36, 81]

    >>> [(x, y) for x in range(3) for y in range(3)]
    [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

    元素配对

     

    girls = ['alice', 'bernice', 'clarice']
    boys = ['chris', 'arnold', 'bob']
    letterGirls = {}
    for girl in girls:
    letterGirls.setdefault(girl[0], []).append(girl)
    print([b+'+'+g for b in boys for g in letterGirls[b[0]]])

    字典推导

    >>> squares = {i:"{} squared is {}".format(i, i**2) for i in range(10)}
    >>> squares[8]
    '8 squared is 64'

    10.三人行

    pass

    这些代码不能运行,因为在Python中代码块不能为空。要修复这个问题,只需在中间的代码
    块中添加一条pass语句即可。
    if name == 'Ralph Auldus Melish':
    print('Welcome!')
    elif name == 'Enid':
    # 还未完成……
    pass
    elif name == 'Bill Gates':
    print('Access Denied')

    del

    在Python中,根本就没有办法删除值,而且你也不需要这样
    做,因为对于你不再使用的值,Python解释器会立即将其删除。

    1. exec
    函数exec将字符串作为代码执行。
    >>> exec("print('Hello, world!')")
    Hello, world!

    >>> from math import sqrt
    >>> scope = {}
    >>> exec('sqrt = 1', scope)
    >>> sqrt(4)
    2.0
    >>> scope['sqrt']
    1
    如你所见,可能带来破坏的代码并非覆盖函数sqrt。函数sqrt该怎样还怎样,而通过exec执
    行赋值语句创建的变量位于scope中。
    请注意,如果你尝试将scope打印出来,将发现它包含很多内容,这是因为自动在其中添加
    了包含所有内置函数和值的字典__builtins__。

    >>> len(scope)
    2
    >>> scope.keys()
    ['sqrt', '__builtins__']

    2. eval
    eval是一个类似于exec的内置函数。

    >>> eval(input("Enter an arithmetic expression: "))
    Enter an arithmetic expression: 6 + 18 * 2
    42

    >>> scope = {}
    >>> scope['x'] = 2
    >>> scope['y'] = 3
    >>> eval('x * y', scope)
    6

    >>> scope = {}
    >>> exec('x = 2', scope)
    >>> eval('x * x', scope)
    4

     

  • 相关阅读:
    C++ 如何判断所调用的重载函数
    C++ 入门5 类和动态内存分配(一)
    c#动态创建ODBC数据源
    设为首页,加入收藏,联系我们
    ASP.NET 2.0中CSS失效
    typedef的四个用途和两个陷阱(转)
    VC++实现应用程序对插件的支持(转)
    DOM无关事件
    How to Migrate from WCF Web API to ASP.NET Web API
    Using ASP.NET Web API with ASP.NET Web Forms
  • 原文地址:https://www.cnblogs.com/joker-hk/p/9690595.html
Copyright © 2011-2022 走看看