In: Computer Science
PYTHON
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
20 pts. |
The Menu() function achieves the goals given above. |
20 pts. |
Base2() takes in an int from the user and accurately converts it to binary |
20 pts. |
Base10() takes in and accurately converts a binary number to a decimal. The binary number is entered by the user. |
20 pts. |
Reverse() is implemented and called correctly. |
20 pts. |
Comments-There should be a comment block at the top that contains:
There should also be a comment before each function explaining
See reverse above. |
Program
Output:
*** Welcome to the conversion program ***
*** Menu ***
1. Convert Binary to Decimal
2. Convert Decimal to Binary
3. Quit
Enter an option (1-3): 1
Enter a Binary number: 1010
Equivalent Decimal number is 10
*** Menu ***
1. Convert Binary to Decimal
2. Convert Decimal to Binary
3. Quit
Enter an option (1-3): 2
Enter a Decimal number: 14
Equivalent Binary number is 1110
*** Menu ***
1. Convert Binary to Decimal
2. Convert Decimal to Binary
3. Quit
Enter an option (1-3): 3
Process finished with exit code 0