【问题标题】:Python program: a tool to convert binary numbers to decimal, and decimal numbers to binary, and a simple text-only menu to add or subtract numbers [closed]Python程序:将二进制数转换为十进制数,将十进制数转换为二进制数的工具,以及用于加减数字的简单纯文本菜单[关闭]
【发布时间】:2026-01-30 03:35:02
【问题描述】:

Python 程序:一个将二进制数转换为十进制数、将十进制数转换为二进制数的工具,以及一个用于加减数字的简单纯文本菜单。

对于创建者,您能否调整代码,使其看起来像您在编辑器中的代码?我看不懂。

 import sys

二进制转十进制

def bintodec(binnum):
     l = len(binnum)
     s = binnum
     dec = 0
     for i in range(0,l):
         b = s[l-i-1]
         dec = dec + int(b)*(2**i)
         return dec

十进制转二进制

 def dectobin(decnum):
     if decnum==0:
         return "00000000"
     bin=""
     while decnum>0:
         bin = str(decnum%2) + bin
         decnum = decnum/2

     if len(bin)%8 != 0:
         n = 8*(len(bin)/8 + 1) - len(bin)
         bin = "0" + bin
         return bin

 def show_menu():
     print ("What do you want to do?")
     print ("1. Enter the first number")
     print ("2. Enter the second number")
     print ("3. Add the two numbers together")
     print ("4. Subtract the second number from the first")
     print ("5. Exit the program\n")
     show_menu()
      inp = input() 
      n1 = "" 
      n2 = "" 
      while inp !=5:
     if inp=="1":
         n1 = str(input("Enter the first number\n"))
         print ("The first number chosen is: " + str(n1) + "\n")
         show_menu()
     if inp=="2":
         n2= str(input("Enter the second number\n"))
         print ("The first number chosen is: " + str(n1))
         print ("The second number chosen is: " + str(n2) +"\n")
         show_menu()
     if inp=="3":
         print ("The sum of the two numbers is: " + dectobin(bintodec(n1) + bintodec(n2)) + "\n")
     exit()
     if inp=="4":
         if bintodec(n2)<bintodec(n1):
             print ("For this selection second number should be greater than or equal to first")
         else:
             print ("The difference beween the two numbers is: " + dectobin(bintodec(n2) - bintodec(n1)) + "\n")
         exit()
     inp = input()

【问题讨论】:

  • 抱歉,我在这里编辑代码时遇到了问题,我的问题是,当我运行代码并输入我的数字(例如 1 + 1)时,它会给我一大串数字跨度>
  • 删除每行开头的所有 >。然后选择代码并按 ctrl-k。
  • 好的,所以你有一些代码要做某事,有什么问题? (即:您遇到的代码有什么问题?)
  • 当我运行代码并输入我的第一个和第二个数字并将它们加在一起时,它会给我一个巨大的数字串作为我的答案,而我所做的只是尝试将 1 + 1 加在一起
  • 这里有一个 repl 的链接。以防万一这里的编辑不正确repl.it/repls/EvergreenPlainAmericanlobster

标签: python


【解决方案1】:

好吧,你去吧 :P 决定使用 switch 对象,因为它很有趣。但是我发现输入'5'很难退出开关

class switch(object):
    value = None
    def __new__(class_, value):
        class_.value = value
        return True

def case(*args):
    return any((arg == switch.value for arg in args))

def bintodec(binnum):
    return int(str(binnum), 2)

def add(first, second):
    try:
        first = int(first,2)
        second = int(second,2)
    except:
        pass
    print('result')
    print(int(first) + int(second))
    print('')

def sub(first, second):
    try:
        first = int(first,2)
        second = int(second,2)
    except:
        pass    
    print('result')
    print(int(second) - int(first))
    print('')


def show_menu():

    while True:
        print ("What do you want to do?")
        print ("1. Enter the first number")
        print ("2. Enter the second number")
        print ("3. Add the two numbers together")
        print ("4. Subtract the second number from the first")
        print ("5. Exit the program\n")            
        ask_for_input = input('Enter Switch\n')
        ask_for_input = int(ask_for_input)

        while switch(ask_for_input):
            if case(1):
                ask_for_1_num = input("Enter the first number\n")
                break
            if case(2):
                ask_for_2_num = input("Enter the second number\n")
                break
            if case(3):
                add(ask_for_1_num, ask_for_2_num)
                break
            if case(4):
                sub(ask_for_1_num, ask_for_2_num)
                break
            if case(5):
                break
            break    

def main():
    show_menu()

if __name__ == '__main__':
    main()        

希望现在可以解决吗?在某些地方可能需要一些工作,我将把它留给你。

【讨论】:

  • 非常感谢,帮了大忙
  • 这个switch的东西到底是什么东西。为什么不直接使用 if/elif 语句?
  • 如果你愿意,你可以,不会很难改变它,我知道它不完全是pythonic,只是想尝试一下。
【解决方案2】:

虽然对你试图做的事情有很多困惑,但我能想到的是:

# Binary To Decimal
def bintodec(binnum):
    return int(str(binnum), 2)

#Decimal To Binary   
def dectobin(x):
    return int(bin(x)[2:])

def ask_for_numbers():
    number_list = 0
    while True:
        ask_for_operand = input('Would you like to add or sub')
        ask_for_number = input('Please enter a number: ')
        try:
            if ask_for_operand == 'add':
                try:
                    number_list += bintodec(ask_for_number)
                except:
                    number_list += int(ask_for_number)
                print(number_list)
            elif ask_for_operand == 'sub':
                try:
                    number_list -= bintodec(ask_for_number)
                except:
                    number_list -= int(ask_for_number)
                print(number_list)
            else:
                return number_list
        except ValueError:
            print("Not Int or Bin")

def main():
    print(ask_for_numbers())

if __name__ == '__main__':
    main()

显然我必须重新开始,不需要十进制到二进制函数。这样做的问题是,如果我想添加十进制“10”,函数 ask_for_numbers() 将希望将其转换为二进制值。也许你可以编辑这段代码来弄清楚。

我希望这会有所帮助:)

【讨论】:

  • 太棒了,我很感激,遗憾的是,我必须有完整的菜单,就像我有它一样,它必须像现在这样要求两个数字,只是希望我能弄清楚为什么我得到那个当我添加或减去大量数字时