zoukankan      html  css  js  c++  java
  • Python条件控制与循环语句

    1. 条件控制

    # if-elif-else结构
    age = 12
    
    if age < 4:
        price = 0
    elif age < 18:
        price = 5
    else:
        price = 10
    
    print("Your admission cost is $" + str(price) + ".")
    
    # Your admission cost is $5.
    

    可以使用多个elif代码块,也可以省略else代码块。

    1.1 使用if语句处理列表

    # 确定列表不是空的
    requested_toppings = []
    
    if requested_toppings:
        for requested_topping in requested_toppings:
            print("Adding " + requested_topping + ".")
        print("
    Finished making your pizza!")
    else:
        print("Are you sure you want to plain pizza?")
        
    # Are you sure you want to plain pizza?
    
    # 使用多个列表
    available_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapple', 'extra cheese']
    
    requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
    
    for requested_topping in requested_toppings:
        if requested_topping in available_toppings:
            print("Adding " + requested_topping + ".")
        else:
            print("Sorry, we don't have " + requested_topping + ".")
    
    print("
    Finished making your pizza!")
    # Adding mushrooms.
    # Sorry, we don't have french fries.
    # Adding extra cheese.
    # 
    # Finished making your pizza!
    

    2. 循环语句

    n = 100
     
    sum = 0
    counter = 1
    while counter <= n:
        sum = sum + counter
        counter += 1
     
    print("1 到 %d 之和为: %d" % (n,sum))
    
    # 1 到 100 之和为: 5050
    

    2.1 while 循环使用 else 语句

    count = 0
    while count < 5:
       print (count, " 小于 5")
       count = count + 1
    else:
       print (count, " 大于或等于 5")
    
    # 0  小于 5
    # 1  小于 5
    # 2  小于 5
    # 3  小于 5
    # 4  小于 5
    # 5  大于或等于 5  
    

    如果你的while循环体中只有一条语句,你可以将该语句与while写在同一行中。

    while(True): print('Hello!')
    

    注意:以上的无限循环你可以使用 CTRL+C 来中断循环。

    2.2 for语句

    languages = ["C", "C++", "Perl", "Python"]
    for x in languages:
    	print (x)
    
    # C
    # C++
    # Perl
    # Python	
    

    2.3 break语句

    n = 1
    while n <= 10:
        if n > 5: # 当n = 6时,条件满足,执行break语句
            break # break语句会结束当前循环
        print(n)
        n = n + 1
    print('END')
    
    # 1
    # 2
    # 3
    # 4
    # 5
    # END
    

    2.4 continue语句

    n = 0
    while n < 10:
        n = n + 1
        if n % 2 == 0: # 如果n是偶数,执行continue语句
            continue # continue语句会直接继续下一轮循环,后续的print()语句不会执行
        print(n)
    
    # 1
    # 3
    # 5
    # 7
    # 9
    

    参考资料:

  • 相关阅读:
    多线程中,上锁的理解
    sql server 2008 联机丛书
    序列化是线程安全的么
    对象化下的编程——字段
    Dic实现工厂模式
    design principle:java 回调与委派/委托机制(转)
    风筝数据结构学习笔记(2)后序遍历二叉树(非递归)
    风筝数据结构学习笔记(1)利用链式存储结构和递归构建二叉树
    吕震宇老师《设计模式系列》
    吕震宇老师《设计模式随笔系列》
  • 原文地址:https://www.cnblogs.com/gzhjj/p/10661008.html
Copyright © 2011-2022 走看看