zoukankan      html  css  js  c++  java
  • 四、python之 if while for

    一、if条件判断

    if  条件判断:
        逻辑操作……
        ……
    else:
        逻辑操作……

    其中"判断条件"成立时(非零),则执行后面的语句,而执行内容可以多行,以缩进来区分表示同一范围。

    else 为可选语句,当需要在条件不成立时执行内容则可以执行相关语句,具体例子如下:

    实例1:

    # if条件判断
    #数据判断 (字符串) 1.是否为空  a.strip
    #if a.strip():
    #Python strip()方法用于移除字符串头尾指定的字符(默认为空格或换行符)。
    #strip()方法语法:
    #str.strip([chars])
    #参数    chars --移除字符串头尾指定的字符。
    #返回值   返回移除字符串头尾指定的字符生成新的字符串。
    
    a="  1 3 "
    print(a.strip())
    if a.strip()=='':
        print("a is null")

    实例2:

    # 判断是否为字典 用isinstance()函数
    # instance()函数来判断一个对象是否是一个已知的类型,类似type()。
    # i四年Stance()与type()区别:
    #  type()不会认为子类是一种父类类型,不考虑继承关系。
    #  isinstance()会认为子类是一种父类类型,考虑继承关系。
    #  如果要判断;两个类型是否相同推荐使用isinstance().
    dict1= {"name":"chenjiahe","age":27}
    a ="hello world"
    if isinstance(dict1, dict):
        print("{0} is dict ".format(dict1))
    #字典与字符串拼接
    print("{0} {1}".format(dict1,a))

    执行结果:

    {'name': 'chenjiahe', 'age': 27} is dict
    {'name': 'chenjiahe', 'age': 27} hello world

    实例3:

    age = input("请输入你的年龄: ")
    if age.strip() != '':
        if  age.strip().isdigit():
            if int(age) >= 18:
                print("你的年龄是{0},你是一个成年人".format(age.strip()))
            else:
                print("你的年龄是{0},你不是一个成年人".format(age))
        else:
            print("请不要输入非数字字符")
    else:
        print("输入空格是没用的")

    捕获异常:

    #捕获异常
    try:
        age = int(input("Please input your age: "))
    except Exception as e:
        print("请只输入数字!")
        exit(1)
    if int(age) >= 18:
        print('adult')
    else:
        print("kids")

     实例4:

    number = int(input("Please input a number: "))
    
    if number > 0:
        print("{0} 是正数".format(number))
    elif number < 0:
        print("{0} 是负数".format(number))
    else:
        print("{0} 是0".format(number))

     二、while循环判断

    python 中while语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务。其基本形式为:

    while 判断条件:
        执行语句……
    判断条件可以是任何表达式,任何非零、或非空(null)的值均为true.执行语句可以是单个语句或语句块。
    当判断条件假false时,循环结束。
    while语句时还有另外两个重要的命令continue,break来跳过循环,continue用于跳过该次循环,break则是用于退出循环。

    实例1:

    while 1:
        age = input("请输入你的年龄: ")
        if age.strip() != '':
            if age.strip().isdigit():
                if int(age) >= 18:
                    print("你的年龄是{0},你是一个成年人".format(age.strip()))
                    break
                else:
                    print("你的年龄是{0},你不是一个成年人".format(age))
                    break
            else:
                print("你输入的是非数字字符,请重新输入")
                continue
        else:
            print("输入空格是没用的,请重新输入")
            continue

     三、for循环

        for循环可以遍历任何序列的项目,如一个列表或者一个字符串。

    语法:

    for i in sequence:
        statements

    实例1:

    for letter in 'python':
        print("当前字母:{0}".format(letter))
    
    
    for i in range(1,10):
        print("{0} x {1} = {2}".format(i,i,i*i))

    结果:

    实例2:99乘法表

    for a in range(1,10):
        for b in range(1,a+1):
            print("{0}x{1}={2}	".format(b,a,a*b),end=' ')
        print()

    结果:

  • 相关阅读:
    html5 video标签如何禁止视频下载
    Redis源代码-数据结构Adlist双端列表
    HTML5分析实战WebSockets基本介绍
    Chromium on Android: Android在系统Chromium为了实现主消息循环分析
    Android AIDL使用特定的解释
    [LeetCode]Maximum Product Subarray
    OC省字典的数组摘要集
    CocoaChina 第四个测试
    Java在的时候,类定义HashSet初始化方法
    WSHPSRS-匹克选择列表生成器-SRS(R12.2.3)
  • 原文地址:https://www.cnblogs.com/chenjiahe/p/9115927.html
Copyright © 2011-2022 走看看