python - loops

作者: Pingouin | 来源:发表于2020-08-27 18:52 被阅读0次

    loops and iteration

    py4E022-025

    While

    while loops are called indefinite loops because they keep going until a logical condition becomes False.

    # break out of a loop
    while True:
        line = input('>')
        if line == 'done':
            break
        print(line)
    print('done!')
    
    # finishing an iteration with contine
    while True:
        line = input('>')
        if line[0] == '#':
            continue # go up back to the tope of loop 
        if line == 'done':
            break # get out of the loop
        print(line)
    print('done!')
    

    for

    definite loops iterate through the members of a set.

    for i in [5,4,3,2,1]: # i is iteration variable
        print(i)
    print('blast off!')
    
    friends = ['ke','xinlei','xjc']
    for friend in friends:
        print('hi',friend)
    print('ok')
    
    # count
    count = 0
    sum = 0
    print('before',count,sum)
    for things in [9,41,12,3,74,15]:
        count += 1
        sum += things
        print(things,count,sum)
    print('after',count,sum)
    
    # a none type
    smallest = None
    print('before',smallest)
    for value in [9,41,12,3,74,15]:
        if smallest is None:
            smallest = value
        elif value < smallest:
            smallest = value
        print(smallest,value)
    print('after',smallest)
    
    # 'is' is stronger than '==' e.g. 0 == 0.00
    # use is for None/ Ture False, not recommended use for integer 
    
    

    condition

    py4E016

    astr = 'hello'
    try:
      print('hello')
      astr = int(astr) #注意此处错误
    except: # 只在try错误的时候触发 每一条
      astr = -1
    print('First', istr)
    

    相关文章

      网友评论

        本文标题:python - loops

        本文链接:https://www.haomeiwen.com/subject/rsvqsktx.html