python 基础教程之3 格式化数据,布尔值,if,布尔逻辑

linux python基础教程 python 3.5

Posted by ivo on March 20, 2018

0x06 格式化数据

  • 常用的 int() str() float()
    >>> x = 5
    >>> y = x + 3
    >>> y = int(str(y) + '2')
    >>> print(y)
    82
    >>> float(y)
    82.0
    

0x07 布尔值

  • python里面的布尔值有两种 True和False
    >>> my_abc = True
    >>> my_abc
    True
    >>> 2 == 3
    False
    >>> 1 != 1
    False
    >>> 'abc' != "cc"
    True
    >>> 5 > 3
    True
    >>> 5 > 5
    False
    >>> 5 >= 5
    True
    >>> 5 <= 5
    True
    >>> 5 <= 5.0
    True
    

0x08 if控制流

  • if语句的格式
    if 判断条件:
    [tab]执行的内容
    
    cat test2.py
    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    if 10 > 5:
    print('good')
    print('end it')
    
    ./test2.py
    good
    end it
    
    >>> num = 12
    >>> if num > 5:
    ...     print("Bigger than 5")
    ...     if num < 47:
    ...             print("Between 5 and 47")
    ...
    Bigger than 5
    Between 5 and 47
    
    >>> num = 7
    >>> if num == 5:
    ...   print("Number is 5")
    ... else:
    ...   if num == 11:
    ...     print("Number is 11")
    ...   else:
    ...     if num == 7:
    ...       print("Number is 7")
    ...     else:
    ...       print("Number isn't 5, 11 or 7")
    ...
    Number is 7
    
    >>> num = 7
    >>> if num == 5:
    ...    print("Number is 5")
    ... elif num == 11:
    ...    print("Number is 11")
    ... elif num == 7:
    ...    print("Number is 7")
    ... else:
    ...    print("Number isn't 5, 11 or 7")
    ...
    Number is 7
    

0x0A 布尔逻辑

  • 与and 或or 非not
    >>> 1 == 1 and 2 == 2
    True
    >>> 1 == 1 and 2 == 3
    False
    >>> 1 != 1 and 2 == 2
    False
    >>> 2 < 1 and 3 >  6
    False
    
    >>> 1 == 1 or 2 == 2
    True
    >>> 1 == 1 or 2 == 3
    True
    >>> 1 != 1 or 2 == 2
    True
    >>> 2 < 1 or 3 >  6
    False
    
    >>> not 1 == 1
    False
    >>> not 1 > 7
    True