首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python从数制到数制的转换

Python从数制到数制的转换
EN

Stack Overflow用户
提问于 2021-02-23 20:50:56
回答 1查看 90关注 0票数 0

在课堂上,我们让任务编写一个脚本,将数字系统转换为数字系统(如从十六进制转换为dual等)。我不期望完整的代码,只是想展示我的代码,它可以工作,但我感觉它很糟糕(我们只有3周的python )。有什么建议可以改进它吗?就像我说的,作业已经完成,并且已经上交了,但我想要提高;)

代码语言:javascript
运行
复制
       if aw == "q" or aw == "1" or aw == "2" or aw == "3" or aw == "4":
            done = False
        else:
            print("\n Keine gültige Auswahl bitte versuchen Sie es erneut ")
    
    return aw

def ag(blacklist):              
    done = True
    while done:
        
        if blacklist !="1":
            print ("(d) Dezimal")
        if blacklist !="2":
            print ("(b) Binär")
        if blacklist !="3":
            print ("(h) Hexadezimal")
        if blacklist !="4":
            print ("(o) Oktal")
        if blacklist !="q":
            print ("(q) Beenden")
            
        print ("")

    
        ag = input("Ihre Wahl")
        if ag == "d" or ag == "b" or ag == "h" or ag == "o" or ag == "q":
            done = False
        else:
            
            print("\n Keine gültige Auswahl bitte versuchen Sie es erneut ")
        return ag
def convertToOctal(decimal):
    # slice off the first two characters and return the rest
    return str(oct(decimal))[2:]

def convertToHex(decimal):
    # slice off the first two characters and return the rest
    return str(hex(decimal))[2:]

def convertToBinary(decimal):
    # slice off the first two characters and return the rest
    return str(bin(decimal))[2:]

def convertToDecimal(number, base, validBases = [2, 8, 16]):
    """
      Returns the number (given in string format) in the specified base
    """
    if base not in validBases:
        raise Exception("Invalid base")
        
    return int(number, base)
EN

回答 1

Stack Overflow用户

发布于 2021-02-23 21:20:27

考虑到您正在学习Python 3周,您做得很好。您只需学习Python中已有的内置函数以及它们的工作方式。

代码语言:javascript
运行
复制
def convertToOctal(decimal):
    # slice off the first two characters and return the rest
    return str(oct(decimal))[2:]

def convertToHex(decimal):
    # slice off the first two characters and return the rest
    return str(hex(decimal))[2:]

def convertToBinary(decimal):
    # slice off the first two characters and return the rest
    return str(bin(decimal))[2:]

def convertToDecimal(number, base, validBases = [2, 8, 16]):
    """
      Returns the number (given in string format) in the specified base
    """
    if base not in validBases:
        raise Exception("Invalid base")
        
    return int(number, base)

您还必须执行一些错误检查(例如,用户是否确实向适当的函数传递了一个有效的数字),但上述代码基本上是程序中的业务逻辑。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66333469

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档