我不知道为什么会这样。也不要告诉我使用python的内置函数,因为这是为某些实际设计而不是实际使用的。它是二进制到十进制的。它与变量'index'
有一个索引错误 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
答案 0 :(得分:1)
这似乎不对
index = 0
while index > 6: #until every power has been checked (in reverse order)
...
你永远不会进入这个循环,是吗?
更好的循环就像是
for i, bit in enumerate(l_bi):
answer += int(bit) * pow(2, 7-i)
另外,既然你刚刚练习,你应该找到一种更好的方法从菜单跳转到功能并返回。你正在进行递归调用,这是浪费堆栈,即你的函数实际上永远不会完成,只是调用越来越多的函数。
答案 1 :(得分:0)
一些修正:
def binary_dec():
anwser = 0
l_bi = str(input('Enter a number in binary up to 7 digits: '))
while len(l_bi) > 7: # LOOP UNTIL LENGTH IS LESS THAN 7
l_bi = str(input('Enter... : '))
power = len(l_bi) - 1 # directly set the power based on length
index = 0
while index < len(l_bi): # CORRECT LOOP CONDITION