zoukankan      html  css  js  c++  java
  • Python

    From:http://interactivepython.org/courselib/static/pythonds/Introduction/ControlStructures.html

    Control Structures

    As we noted earlier, algorithms require two important control structures: iteration and selection.

    • Iteration
      • while
    >>> counter = 1
    >>> while counter <= 5:
    ...     print("Hello, world")
    ...     counter = counter + 1
    
    
    Hello, world
    Hello, world
    Hello, world
    Hello, world
    Hello, world
      • for
    >>> for item in [1,3,6,2,5]:
    ...    print(item)
    ...
    1
    3
    6
    2
    5

    >>> for item in [1,3,6,2,5]:
    ...    print(item)
    ...
    1
    3
    6
    2
    5

    wordlist = ['cat','dog','rabbit']
    letterlist = [ ]
    for aword in wordlist:
    for aletter in aword:
    letterlist.append(aletter)
    print(letterlist)

    • Selection
    Selection statements allow programmers to ask questions and then, based on the result, perform different actions.
      • ifelse
    if n<0:
       print("Sorry, value is negative")
    else:
       print(math.sqrt(n))

    if score >= 90:
       print('A')
    else:
       if score >=80:
          print('B')
       else:
          if score >= 70:
             print('C')
          else:
             if score >= 60:
                print('D')
             else:
                print('F')


    if score >= 90:
       print('A')
    elif score >=80:
       print('B')
    elif score >= 70:
       print('C')
    elif score >= 60:
       print('D')
    else:
       print('F')
      • if
        if n<0:
           n = abs(n)
        print(math.sqrt(n))
         
      • list comprehension
    >>> sqlist=[]
    >>> for x in range(1,11):
             sqlist.append(x*x)
    
    >>> sqlist
    [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
    >>>


    >>> sqlist=[x*x for x in range(1,11)]
    >>> sqlist
    [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
    >>>
    >>> sqlist=[x*x for x in range(1,11) if x%2 != 0]
    >>> sqlist
    [1, 9, 25, 49, 81]
    >>>


    >>>[ch.upper() for ch in 'comprehension' if ch not in 'aeiou']
    ['C', 'M', 'P', 'R', 'H', 'N', 'S', 'N']
    >>>

     

  • 相关阅读:
    洛谷—— P2234 [HNOI2002]营业额统计
    BZOJ——3555: [Ctsc2014]企鹅QQ
    CodeVs——T 4919 线段树练习4
    python(35)- 异常处理
    August 29th 2016 Week 36th Monday
    August 28th 2016 Week 36th Sunday
    August 27th 2016 Week 35th Saturday
    August 26th 2016 Week 35th Friday
    August 25th 2016 Week 35th Thursday
    August 24th 2016 Week 35th Wednesday
  • 原文地址:https://www.cnblogs.com/keepSmile/p/7879223.html
Copyright © 2011-2022 走看看