python - Python从数字系统转换为数字系统
问题描述
在课堂上,我们获得了编写脚本以将数字系统转换为数字系统的任务(例如从十六进制转换为对偶等)。我不期望完整的代码,只是想展示我的,它可以工作,但我觉得它很糟糕(我们只有 3 周的 python)。有什么改进的建议吗?就像我说的,作业已经完成并且已经上交,但我想改进;)
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)
解决方案
考虑到你正在学习 Python 3 周,你做得很好。你只需要学习 Python 中已有的内置函数以及它们是如何工作的。
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)
您还必须做一些错误检查(例如,用户是否真的向相应的函数传递了一个有效数字),但上面的代码基本上是您在程序中的业务逻辑。
推荐阅读
- microsoft-graph-api - 在“oneDrive.item”类型上获取“属性 'openWith' 不是导航属性。” 尝试访问工作簿 api 时
- windows - 从不同的 powershell 会话访问在一个 powershell 会话中创建的远程 powershell 会话
- python-3.x - 我想拆分数据并按行和列获取值
- firebase - Firestore 超时
- javascript - 大量的 mongodb 动态集合对项目来说是一件坏事,并且对性能有影响吗
- c - 当应用于链表中的指针时,AND 运算符是什么意思?
- c# - 如何使用@Html.ActionLink 显示带参数的索引视图?
- javascript - 用服务器端渲染反应路由器模式路由
- javascript - 奇怪的javascript循环行为
- android-fragments - 在片段中使用 RecyclerView 时询问权限时应用程序崩溃