我是python的新手,我想创建二进制到十进制转换器和十进制到二进制转换器。
然而用户想要转换的二进制数只能是八位数,并且必须是有效的二进制数,而用户想要转换的十进制数只能是正数且最多为255。
我想出了这段代码,我坚持使用'但是'部分。
import time
def program():
a = input ("Would you like to convert Denary To Binary (D) or Binary To Denary (B)? ")
if a == ("D") :
def denary():
print("The denary number you want to convert, can only be a positive number up to 255")
time.sleep(2)
e= int(input("What number would you like to convert into Binary? "))
if e < 255 or e==255 or e >= 0:
print(bin(e)[2:].zfill(8))
again=int(input("Would you like to go again YES[1] NO[2]"))
if again==(1):
program()
else:
print ("Thank you for using the program")
else:
denary()
denary()
elif a == ("B"):
def binary():
print("The binary number you want to convert, can only be eight digits long and can only be a valid binary, number consiting of 0's and 1's")
time.sleep(2)
c = int(input("What Binary number would you like to convert into Denary? "))
if len(c) >8 and c== '0' or '1':
convert= lambda b: str(int(b, 2))
print(c + " is " + convert(c) + " in Denary")
again=int(input("Would you like to convert a number again YES[1] NO[2]"))
if again==(1):
program()
else:
print ("Thank you for using the program")
else:
binary()
binary()
else:
program()
program()
答案 0 :(得分:1)
以下是应该让您前进的基本转换功能:
def dec2bin(N):
if not N:
return ''
else:
return dec2bin(N//2) + str(N%2)
def bin2dec(b):
answer = 0
for char in b:
answer *= 2
answer += int(char)
return answer
def program():
answer = input("Do you want to convert decimal to binary (D) or ...: ")
if answer == "D":
N = int(input("Enter your number: "))
print("The binary of %s is %s" %(N, dec2bin(N)))
# remainder of the UI logic goes here
答案 1 :(得分:1)
if e < 255 or e==255 or e >= 0:
您不希望or
在这里。如果至少有一个条件为真,则将采用该分支。 1000满足e >= 0
,因此1000将通过检查。 -1000满足e < 255
,因此-1000将通过检查。事实上,每个数字都会在这里传递。你想要
if e >= 0 and e <= 255:
或者,使用Python的比较链,
if 0 <= e <= 255:
if len(c) >8 and c== '0' or '1':
这没有任何意义。
首先,c
已经是int
;你试图把它当作一个字符串来操纵它。
其次,长度测试不应该检查长度大于是否超过8.如果您需要完全匹配或{{1},则应为== 8
如果长度不超过8个。
第三,<= 8
之后的部分内容毫无意义。 and
不会测试x == y or z
是否等于x
或y
中的一个。它被解释为z
,这通常是无稽之谈。
最后,即使(x == y) or z
测试c== '0' or '1'
是c
还是'0'
之一,这仍然不是一件有意义的事情。如果您要测试'1'
中的所有字符是c
还是'0'
,您可以将'1'
与生成器表达式一起使用:
all(char in('0','1')for c in c)
解决所有这些问题,我们有以下几点:
all
答案 2 :(得分:0)
利用你的内置资源!
dec to bin:
def to_bin(n): #assuming n is a str
"""If the str n represents a number in the range [0, 256), return a
binary string representation of that number, otherwise raise a ValueError
"""
if 0 <= int(n) < 256: # if n is in the valid range
return bin(int(n))[2:] #builtin :p
else:
raise ValueError('number must be in range [0, 256)')
bin to dec
def to_dec(n):
"""If the str n is at most 8 characters long and consists only of '0' and
'1' characters, return the decimal string representation of it, otherwise
raise a ValueError
"""
if len(n) <= 8 all(c in ('0', '1') for c in n):
return str(int(n, 2))
else:
raise ValueError('binary number must be <= 8 digits and consist of 0 and 1')