Я успешно сделал программу, которая преобразует двоичный код в десятичный. У меня есть сильное чувство, что это можно сделать проще и эффективнее, чем то, как я его создал. Это то, что у меня есть:Как я могу сделать свою программу более эффективной?
#Binary to Decimal Conversion
#Input Data and assign variables
def main():
binary = input("Enter rhe binary number you'd like to convert: ")
x = "1"
y = "0"
num1 = 0
num2 = 0
num3 = 0
num4 = 0
num5 = 0
num6 = 0
num7 = 0
num8 = 0
#Error Handling for incorrect number of characters
while len(binary)!= 8:
print("Please enter a valid value")
binary = input("Enter rhe binary number you'd like to convert: ")
if binary == 8:
break
#Processing the data and conversion
#Checks to see if character 1 in the string binary is equal to "1" or "0"
if binary[0] == "1":
num1 = 128
elif binary[0] == "0":
num1 = 0
else:
print('Error, value 1 is not = to "1" or "0"')
main()
if binary[1] == "1":
num2 = 64
elif binary[1]:
num2 = 0
else:
print('Error, value 2 is not = to "1" or "0"')
main()
if binary[2] == "1":
num3 = 32
elif binary[2] == "0":
num3 = 0
else:
print('Error, value 3 is not = to "1" or "0"')
main()
if binary[3] == "1":
num4 = 16
elif binary[3] == "0":
num4 = 0
else:
print('Error, value 4 is not = to "1" or "0"')
main()
if binary[4] == "1":
num5 = 8
elif binary[4] == "0":
num5 = 0
else:
print('Error, value 5 is not = to "1" or "0"')
main()
if binary[5] == "1":
num6 = 4
elif binary[5] == "0":
num6 = 0
else:
print('Error, value 1 is not = to "1" or "0"')
main()
if binary[6] == "1":
num7 = 2
elif binary[6] == "0":
num7 = 0
else:
print('Error, value 1 is not = to "1" or "0"')
main()
if binary[7] == "1":
num8 = 1
elif binary[7] == "0":
num8 = 0
else:
print('Error, value 1 is not = to "1" or "0"')
main()
#output and rerun
print("The converted number is: ", num1 + num2 + num3 + num4 + num5 + num6 + num7 + num8)
choice = ' '
while choice != "1" and choice != "2":
choice = input("Would you like to perform another coversion?:\n[1]Yes\n[2]Naw\n")
if choice == "1":
main()
elif choice == "2":
exit()
else:
print("Error please select [1] or [2]")
main()
Я думал, что можно будет запустить фактическую часть преобразования с помощью цикла? Кроме того, я довольно новичок в python ... да, я сначала сделал это в Google. Кроме того, весь материал под основным() IS отступом, у меня были проблемы с форматированием моего кода в stackoverflow.
Если это ** рабочий код **, который, по вашему мнению, может быть улучшен, рассмотрите [codereview.se]. И прочитайте http://stackoverflow.com/editing-help. – jonrsharpe
@jonrsharpe Спасибо! –