如何检查输入是否为二进制格式(1 和 0)? [英] How to check if a input is in binary format(1 and 0)?

查看:25
本文介绍了如何检查输入是否为二进制格式(1 和 0)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个程序,但是如果用户输入不是二进制格式,我想添加一个例外.我已经尝试了很多次添加例外,但我似乎无法让它工作.下面是程序代码.如果有人能提供帮助,我将不胜感激.

I have made a program however I wanted to add an exception if the user inputs is not in a binary format. I have tried many times adding exceptions but I can't seem to get it to work. The below is the program code. I would appreciate if someone could help.

import time
error=True
n=0
while n!=1:
    print"***Welcome to the Bin2Dec Converter.***\n"
    while error:
        try:
            bin2dec =raw_input("Please enter a binary number: ")
            error=False
        except NameError: 
            print"Enter a Binary number. Please try again.\n"
            time.sleep(0.5)
        except SyntaxError: 
            print"Enter a Binary number. Please try again.\n"
            time.sleep(0.5)


        #converts bin2dec
        decnum = 0 
        for i in bin2dec: 
            decnum = decnum * 2 + int(i)
            time.sleep(0.25)
        print decnum, "<<This is your answer.\n" #prints output

推荐答案

如果您正在避免 Python 的内置方式 (int(..., 2)),作为学习练习,那么一个合乎逻辑的 Pythonic 方法是创建您自己的错误类并将错误检查构建到您的转换函数中.

If you are avoiding Python's built in way of doing this (int(..., 2)), as a learning exercise, then a logical and Pythonic approach would be to make your own error class and build the error checking in to your conversion function.

class BinaryError(Exception):
    def __str__(self):
        return "Not a valid binary number"

def bin2dec(input_string):
    r = 0
    for character in input_string:
        if character == '0':
            r = r * 2
        elif character == '1':
            r = r * 2 + 1
        else:
            raise BinaryError()
    return r

while True:
    try:
        print bin2dec(raw_input("Please enter a binary number: "))
    except BinaryError:
        print "Enter a Binary number. Please try again.\n"
    else:
        break

这篇关于如何检查输入是否为二进制格式(1 和 0)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆