我不知道为什么这被打破。也不要告诉我使用python的内置函数,因为这是为某些练习设计的,而不是实际使用。它是二进制到十进制被打破。它与变量“指标”损坏的二进制转换器。索引错误
print('Please choose from the list below:')
print('')
print('1) Convert from decimal/denary to binary; ')
print('2) Covert from binary to denary/decimal; ') #Main Menu
print('3) Infomation and settings (coming soon);')
print('4) Exit. ')
print('')
menu_choice = str(input('Enter your choice here: ')) #User inputs choice here
if menu_choice == '1':
dec_binary()
elif menu_choice == '2':
binary_dec()
elif menu_choice == '3':
print('By Callum Suttle')
else:
return 'Thank You'
def dec_binary(): #Module 1: decimal to binary
dec = int(input('Enter a number in decimal up to 255: ')) #Checks The number is an ok size, could be made bigger
while dec > 255:
dec = int(input('Enter a number up to 255, no more: '))
power = int(7) #change 7 to make bigger by 1 digit
convert = []
while power > -1: #until power goes below zero
if dec - pow(2, power) >= 0: #if entered number subtract 2 to the power of var-pow returns posotive number
convert.append(1)
power -=1 # add a 1
dec = dec - pow(2, power) >= 0
else:
convert.append(0)#if not add a zero
power -=1
print('')
print(convert) # print completed number
print('')
binary_decimal_converter() #back to main menu
def binary_dec():
anwser = 0
l_bi = str(input('Enter a number in binary up to 7 digits: '))
while len(l_bi) != 7: #checks for correct length
l_bi = str(input('Enter a number in binary up to 7 digits, you may add zeros before: '))
power = 7 #size can be increased by using this
index = 0
while index > 6: #until every power has been checked (in reverse order)
if l_bi[index] == '1': #if the digit is equal to 1
anwser += pow(2, power) #add that amount
power -= 1 #take the power to check next #why is this broken
index += 1 # add another index to check previous
else:
power -= 1 #as above
index += 1 #/\
print('')
print(anwser) #prints result
print('')
binary_decimal_converter() #main menu
不完全是关系到你的问题,但这里有设计很差。顶部的代码是一个名为binary_decimal_converter()的函数(我假设你在粘贴时错过了def行)。什么是错误的是,你试图通过在每次转换之后调用GOTO来有效地完成GOTO,但由于它实际上是一个函数调用,而不是GOTO,因此您将递归地堆叠函数调用。您应该将菜单置于while循环中,当选择Exit选项时,其条件变为false。 –
你应该分开你的代码,使其具有只*执行转换(没有输入或输出)的函数,然后有一些接口函数来处理实际的用户交互,并调用转换函数。这样,您可以单独测试您的转换函数,而无需一直执行所有交互逻辑。 – poke