Python3基础 二、八、十、十六进制转换

  •        Python : 3.7.3
  •          OS : Ubuntu 18.04.2 LTS
  •         IDE : pycharm-community-2019.1.3
  •       Conda : 4.7.5
  •    typesetting : Markdown

code

"""
@Author : 行初心
@Date   : 2019/7/6
@Blog   : www.cnblogs.com/xingchuxin
@Gitee  : gitee.com/zhichengjiu
"""


def main():
    # 2 to 8 10 16
    bin_num = 0b111
    print(oct(int(str(bin_num))))
    print(int(bin_num))
    print(hex(int(str(bin_num))))

    print()

    # 8 to 2 10 16
    oct_num = 0o011
    print(bin(int(str(oct_num))))
    print(int(oct_num))
    print(hex(int(str(oct_num))))

    print()

    # 10 to 2 8 16
    int_num = 15
    print(bin(int_num))
    print(oct(int_num))
    print(hex(int(str(int_num))))

    print()

    # 16 to 8 10
    hex_num = 0xff
    print(bin(hex_num))
    print(int(hex_num))
    print(oct(int(str(hex_num))))


if __name__ == '__main__':
    main()

result

/home/coder/anaconda3/envs/py37/bin/python /home/coder/PycharmProjects/NumericalComputation/demo.py
0o7
7
0x7

0b1001
9
0x9

0b1111
0o17
0xf

0b11111111
255
0o377

Process finished with exit code 0

source_code

def bin(*args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 
    """
    Return the binary representation of an integer.
    
       >>> bin(2796202)
       '0b1010101010101010101010'
    """
    pass

def oct(*args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 
    """
    Return the octal representation of an integer.
    
       >>> oct(342391)
       '0o1234567'
    """
    pass

def hex(*args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 
    """
    Return the hexadecimal representation of an integer.
    
       >>> hex(12648430)
       '0xc0ffee'
    """
    pass

resource

  • [文档 - English] docs.python.org/3
  • [文档 - 中文] docs.python.org/zh-cn/3
  • [规范] www.python.org/dev/peps/pep-0008
  • [规范] zh-google-styleguide.readthedocs.io/en/latest/google-python-styleguide/python_language_rules
  • [源码] www.python.org/downloads/source
  • [ PEP ] www.python.org/dev/peps
  • [平台] www.cnblogs.com
  • [平台] gitee.com


Python具有开源、跨平台、解释型、交互式等特性,值得学习。
Python的设计哲学:优雅,明确,简单。提倡用一种方法,最好是只有一种方法来做一件事。
代码的书写要遵守规范,这样有助于沟通和理解。
每种语言都有独特的思想,初学者需要转变思维、踏实践行、坚持积累。

原文地址:https://www.cnblogs.com/xingchuxin/p/11142054.html