[英]I need to write a python code to accept number from user and convert it to binary without using functions or bin?
在Python中從十進制到二進制
我做了這段代碼,我在答案的末尾得到了零(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='')
我的輸出:輸入數字:42 1010100
我不需要最后的零
輸入電話號碼:42 101010
更好的編隊:
num = int(input("Enter a number: "))
a = ''
while num > 0:
a += str(num % 2)
num //= 2
print(a[::-1])
Enter a number: 42
101010
作為一個初學者,您應該注意自己的編程習慣,以使您的代碼更簡明易懂。
設置a=""
並刪除a = str(a)應該可以解決您的問題
與其將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.