美文网首页
判断条件

判断条件

作者: ALuckyLive | 来源:发表于2020-08-21 16:53 被阅读0次
    输入年龄,根据年龄条件判断符合与否
    age = 20
    if age >= 18:
        print ('your age is:',age)
        print ('adult')
    
    your age is: 20
    adult
    
    根据python的缩进规则及if语句的中的判断条件,使用else,如下
    age = 15
    if age >= 18:
        print ('your age is:',age)
        print ('adult')
    else:
        print ('your age is:',age)
        print ('teenager')
    
    your age is: 15
    teenager
    
    使用elfi语句做判断
    age = 3
    if age >= 18:
        print ('adult')
    elif age >= 6:
        print ('teenager')
    else:
        print ('kid')
    
    kid
    
    • input的使用
    birth = input('birth:')
    if birth < 2000:
        print ('00前')
    else:
        print ('00后')
    
    birth:1988
    
    
    
    ---------------------------------------------------------------------------
    
    TypeError                                 Traceback (most recent call last)
    
    <ipython-input-14-e5b461b8929a> in <module>()
          1 birth = input('birth:')
    ----> 2 if birth < 2000:
          3     print ('00前')
          4 else:
          5     print ('00后')
    
    
    TypeError: '<' not supported between instances of 'str' and 'int'
    

    birth值为str,字符类型无法对比,只有转换成数字类型才可以对比

    s = input('birth:')
    birth = int(s)
    if birth < 2000:
        print ('00前')
    else:
        print ('00后')
    
    birth:1999
    00前
    
    s = input('birth:')
    birth = int(s)
    if birth < 2000:
        print ('00前')
    else:
        print ('00后')
    
    birth:abc
    
    
    
    ---------------------------------------------------------------------------
    
    ValueError                                Traceback (most recent call last)
    
    <ipython-input-16-69188189e7f4> in <module>()
          1 s = input('birth:')
    ----> 2 birth = int(s)
          3 if birth < 2000:
          4     print ('00前')
          5 else:
    
    
    ValueError: invalid literal for int() with base 10: 'abc'
    

    相关文章

      网友评论

          本文标题:判断条件

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