Aug-26-2023, 12:53 PM
Python beginner here--
I wrote a practice program that converts decimal numbers to binary and vice versa. It works great! For example:
Thank you in advance for any help!
I wrote a practice program that converts decimal numbers to binary and vice versa. It works great! For example:
>>> Enter 0 to convert decimal (denary) to binary,
or enter 1 to convert binary to decimal: 1
Enter a number in binary to convert to decimal (denary): 1000101
The number 1000101 expressed in decimal (denary) is: 69
Would you like to perform another conversion? (y/n): y
>>> Enter 0 to convert decimal (denary) to binary,
or enter 1 to convert binary to decimal: 0
Enter a number in decimal (denary) to convert to binary: 69
The number 69 expressed in binary is: 1000101 However, I noticed that I hadn't entered a condition if the user enters a non-binary number when binary is requested. This returns a ridiculous response as follows:>>> Enter 0 to convert decimal (denary) to binary,
or enter 1 to convert binary to decimal: 1
Enter a number in binary to convert to decimal (denary): 69
The number 69 expressed in decimal (denary) is: 21 So I attempted to write a simple conditional to exclude this possibility and simply re-request the input if non-binary numbers are entered, as follows. I also tried iterating over the whole string (for z in range(len(binNum)), etc). def binToDec():
binNum = input("Enter a number in binary to convert to decimal (denary): ")
for z in binNum:
if z != (0 or 1):
print("Please enter a valid binary number")
return binToDec()
denNum = 0
for i in range(len(binNum)):
denNum += (int(binNum[-1*(i+1)])*(2**i))
print()
print(f"The number {binNum} expressed in decimal (denary) is: {denNum}")
return True
binToDec() In every case that I tried, binary digits trigger the return clause the same as non-binary digits. I can't figure out why this is happening. It seems like a very simple and straightforward problem, yet it is eluding me.Thank you in advance for any help!
