In this lab we will design a menu-based program. The program will allow users to decide if they want to convert a binary number to base 10 (decimal) or convert a decimal number to base 2 (binary). It should have four functions menu(), reverse(), base2(), and base10(). Each will be outlined in detail below. A rubric will be included at the bottom of this document.
Menu()
The goal of menu() is to be the function that orchestrates the flow of the program. menu() should be the first thing called and should do the following:
Base2()
This function should take a number from the user and convert it into its binary representation then print it to the user. You can use your code from Lab1.
Base10()
This function should prompt the user for a binary number represented by a string and calculate the decimal number. Base10() should do the following:
for i in range(0,len(st)):
sum+=(int(st[i])*(2**i))
print(sum)
Remember that len returns the number of characters in a string and we can access a character by using the string name and an index number. st[0] would return the first character of the string in variable st. If we think about the conversion, we take the number and multiple by 2 raised to the power of the position number. If we reverse the string, we can use the index number as this position number because the string is indexed left-to-right. Which is the opposite of number positions are right-to-left. Thus, I can be used as our exponent.
Reverse()
#Name: Reverse
#Input: String s
#Output: String r
#Description: This function takes a string as input and reverses that string
#returning it as output.
def reverse(s):
r=""
for i in s:
r=i+r
return r
If you have any doubts, please give me comment...
def menu():
print("Convert a binary number to base 10 (decimal) or convert a decimal number to base 2 (binary)")
print("1. Convert Binary to Decimal")
print("2. Convert Decimal to Binary")
print("3. Quit")
def base2():
num = int(input("Enter decimal number: "))
st = ""
while num>0:
st = str(num%2)+st
num = num//2
print("In Binary",st)
def base10():
st = input("Enter binary number: ")
st = reverse(st)
sum = 0
for i in range(0,len(st)):
sum+=(int(st[i])*(2**i))
print("In Decimal:",sum)
def reverse(s):
r=""
for i in s:
r=i+r
return r
def main():
while True:
menu()
choice = int(input("Enter choice:"))
if choice==1:
base10()
elif choice==2:
base2()
elif choice==3:
break
else:
print("Invalid input")
print()
if __name__ == "__main__":
main()
Get Answers For Free
Most questions answered within 1 hours.