• python学习笔记二:流程控制


    一、if else:

    #!/usr/bin/python
    x = int(raw_input('please input:'))
    
    
    if x >= 90:
        if x >= 95:
            print 'a+'
        else:
            print 'a'
    elif x >= 80:
        if x >= 85:
            print 'b+'
        else:
            print 'b'
    elif x >= 70:
        if x >= 75:
            print 'c+'
        else:
            print 'c'
    else:
        if x >= 60:
            print 'd+'
        else:
            print 'bad'

    二、逻辑运算符 and or not

    #!/usr/bin/python
    x = int(raw_input('please input x:'))
    y = int(raw_input('please input y:'))
    
    
    if x >= 90 and y >= 90:
        print 'a'
    elif x >= 80 or y >= 80:
        print 'b'
    elif not x < 60 and (not y < 60):
        print 'c'
    else:
        print 'bad'

    三、for

    序列:

    #!/usr/bin/python
    
    s = "hello python"
    
    for x in s:
        print x
    
    for index in range(len(s)):
        print s[index]

    字典:

    #!/usr/bin/python
    
    dic = {'a':1,'b':2,'c':3}
    
    for x in dic:
        print x,dic[x]
    
    for k,v in dic.items():
        print k,v

    控制

    else:for正常执行完会执行else中的内容,否则不会(如下面的代码执行过程按Ctrl+c)

    #!/usr/bin/python
    import time
    
    for x in range(10):
        print x
        time.sleep(1)
    else:
        print 'end'

    break:跳出当前这层循环

    #!/usr/bin/python
    for x in range(10):
        print x
        if x == 6:
            break
    else:
        print 'end'

    这里不会执行else中的内容

    pass:占位

    exit:退出

    #!/usr/bin/python
    for x in range(10):
        print x
        if x == 2:
            print 'hello',x
            continue
        if x == 4:
            pass
        if x == 5:
            exit()
        if x == 6:
            break
        print '*'*10
    else:
        print 'end'

    四、while

     当条件失败,正常结束会执行,执行break后else中不执行

    #!/usr/bin/python
    
    x = 'hello'
    
    while x != "q":
        print x
        x = raw_input('please input something,q for quit:')
        if not x:
            break
    else:
        print 'ending'
  • 相关阅读:
    Ui——创建视图的方法及过程
    iOS设计模式----原型模式
    浅谈OC中排序的方法
    Solid Dominoes Tilings (轮廓线dp打表 + 容器)
    Shell Necklace (dp递推改cdq分治 + fft)
    Rigid Frameworks (画图二分图规律 + DP + 数学组合容斥)
    PowMod (欧拉推式子 + 指数循环节)
    Necklace (全排列 + 匈牙利)
    GCD (RMQ + 二分)
    Game (思维)
  • 原文地址:https://www.cnblogs.com/lurenjiashuo/p/python-note-ifelse-for-while.html
Copyright © 2020-2023  润新知