[英]I need to write a python code to accept number from user and convert it to binary without using functions or bin?
Decimal to binary in Python 在Python中从十进制到二进制
I did this code and I am getting a zero(0) at the end of the answer I don't want that zero 我做了这段代码,我在答案的末尾得到了零(0),我不想那个零
num=int(input("Enter a number:"))
a=0
a=str(a)
while num>0:
a=a+str(num%2)
num=int(num/2)
print(a[::-1],end='')
My Output : Enter a number:42 1010100 我的输出:输入数字:42 1010100
I don't need the final zero I need 我不需要最后的零
Enter a number:42 101010 输入电话号码:42 101010
A better formation: 更好的编队:
num = int(input("Enter a number: "))
a = ''
while num > 0:
a += str(num % 2)
num //= 2
print(a[::-1])
Enter a number: 42
101010
As a beginner, you should pay attention to your programming habits to make your code more concise and readable. 作为一个初学者,您应该注意自己的编程习惯,以使您的代码更简明易懂。
设置a=""
并删除a = str(a)应该可以解决您的问题
Rather than initialize a
to "0"
, just initialize it to the empty string: 与其将
a
初始化为"0"
,不如将a
初始化为空字符串:
num=int(input("Enter a number:"))
a=""
while num>0:
a=a+str(num%2)
num=int(num/2)
print(a[::-1],end='')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.