python - 如何限制 python 中的输入,使其只允许 0 或 1?

标签 python

我在 python 中有一个二进制转换器,我想知道如何将我的输入限制为仅某些数字,在这种情况下。只有 1 或 0。所以 101010001 是有效的,但 44 不是例如。谢谢。

最佳答案

您也可以尝试将其转换为二进制整数,如果失败则打印消息。

query = raw_input("enter binary number ")

try:
    is_bin = int(query,2)
    is_bin = True
    print "correct number"
except ValueError:
    is_bin = False
    print "not a binary number"

关于python - 如何限制 python 中的输入,使其只允许 0 或 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22559328/

相关文章:

python - 在计算 networkx 中的传出和传入边缘时,len 抛出 'dict_keyiterator' 没有 len()

python - 数据框中缺少数据

python - unittest.mock.补丁 : Context manager vs setUp/tearDown in unittest

python - 在 pandas 数据框中使用文本字符串数据进行条件数据选择

python - FastAPI: ModuleNotFoundError: 没有名为 'uvicorn' 的模块

java - 构建套接字通信以最小化数据传输

python - 如果 pymongo 中不存在,如何创建带索引的集合?

python - 如何用HTML显示10万行以上的数据库查询结果?

带别名的 Python switch 语句

python - 在 Pandas 数据框中分配新列标签时出现长度不匹配错误