简体   繁体   English

我需要编写一个python代码来接受用户的数字并将其转换为二进制而不使用函数或bin吗?

[英]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.

相关问题 在 python 中不使用 bin() 的数字的二进制表示 - binary representation of a number without using bin() in python 我需要帮助在我的代码中将二进制转换为十进制而不使用 bin - I need help converting binary to decimal in my code without using bin 如何在不使用bin函数的情况下使用python将二进制转换为十进制 - how to convert binary to decimal using python without using the bin function 如何在不使用bin方法的情况下将二进制转换为十进制 - how can I convert binary to decimal without using bin method 如何使用python将十进制数转换为没有0b的二进制数 - How to convert decimal number to binary without 0b using python 不使用内置 bin 函数将整数转换为二进制 - Convert an integer to binary without using the built-in bin function 我试图在不使用 bin 的情况下将十进制数转换为二进制数 - Im trying to make a decimal to binary number without using bin 如何使用bin()方法将列表的所有元素转换为python中的二进制文件? - How do I convert all the elements of a list to binary in python using bin() method? 如何在不使用 Python 列表的情况下找到最大和最小数字?(用户要写数字) - How can I find max and min number without using lists in Python?(user is going to write the numbers) Python:二进制计数,不使用内置函数 - Python: Binary Counting without using inbuilt functions
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM