[英]I'd like to extend my code however I don't know how to go about it
I am fairly new to python and have recently learned how to convert from binary to denary vice versa.我对 python 相当陌生,最近学习了如何从二进制转换为 denary,反之亦然。 I'd like to make a program that allows me to put in a number (binary or denary) and for it to convert to one or the other.我想制作一个程序,允许我输入一个数字(二进制或十进制)并将其转换为一个或另一个。 - Example- convert a binary number to denary vice versa. - 示例 - 将二进制数转换为 denary,反之亦然。 I have already figured out how to make the program convert from binary to denary however I want to make it so someone can convert from denary to binary.我已经想出了如何使程序从二进制转换为 denary 但是我想这样做以便有人可以从 denary 转换为二进制。 I am not too sure how to go about this.我不太确定如何解决这个问题。 This is a piece of my code, if someone could kindly guide me that would be great.这是我的一段代码,如果有人可以指导我,那就太好了。
def add2():
binary = input('enter a number in binary: ')
decimal = 0
for digit in binary:
decimal= decimal*2 + int(digit)
print ("This is the decimal equivalent" , decimal,)
Call each function...调用每个函数...
def binary_to_decimal(num):
return int("{0:d}".format(num), 2)
def decimal_to_binary(num):
return int("{0:b}".format(num))
If you wanted to stick with your format, you could add another function...如果你想坚持你的格式,你可以添加另一个功能......
denary = int(input("enter a number in denary:"))
binary=""
while denary > 0:
binary = str(denary % 2) + binary
denary = denary//2
print("Your binary number is: " + binary)
Converting denary into binary:将 denary 转换为二进制:
denary= int(input('Denary: '))
binary= [0,0,0,0]
while denary>0:
for n,i in enumerate(binary):
if denary//(2**(3-n))>=1:
binary[n]= 1
denary -= 2**(3-n)
print(denary)
print (binary)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.