如果十六进制仅使用1-9和a-f,我怎么才让我的程序继续?

时间:2017-11-19 10:41:47

标签: python

此代码用于将十六进制转换为(十进制)

我不明白如果字母达到f

,如何只允许程序继续
def option6():
    print("\n")
    print("----------------HEXADECIMAL-DENARY-----------------")
    #converts the entered hexadecimal (in base 16) into a integer using the int function
    hexa = input("Please Enter a Hexadecimal : ")

    if hexa ==("1" or "3" or "4" or "5" or "6" or "7" or "8" or "9" or "a" or "b" or "c" or "d" or "e" or "f"):
        denary = int(hexa,16)
        print("Your Denary number is : ",denary)
        print("\n")
        print("===================================================")
        menu=input("Would You Like To Return To The Selection Menu?(Y,N) : ").upper()
        if menu == "Y".upper():
            main()
        elif menu == "N".upper():
            print("\n")
            print("==================================")
            print("You Denary number is: ")
            print(denary)
            print("Thank You For Your Time!")

    else:
        print("Not In Range")
        option6()

2 个答案:

答案 0 :(得分:2)

打开一个交互式python shell(即在没有参数的终端中运行'python'),并输入x

你看到了什么?

"1" or "3" or "4" or "5" or "6" or "7" or "8" or "9" or "a" or "b" or "c" or "d" or "e" or "f"

完全。如果>>> "1" or "3" or "4" or "5" or "6" or "7" or "8" or "9" or "a" or "b" or "c" or "d" or "e" or "f" '1' 可以转换为a or b,则表达式a评估为a,否则评估为True。因此,b支票会缩减为if

你应该写更长的if hexa == "1":。或使用hexa == "1" or hexa == "3" or ...之类的in关键字。或者,由于右侧是所有单个字符串,您可以使用hexa in ["1", "3", "4", "5", ...],因为字符串也可以按字符迭代,而字符本身就是字符串。

如果要解析hexa in "134567..."识别的任何十六进制数,您只需捕获int()例外:

ValueError

答案 1 :(得分:0)

我猜你使用Python 3.x进行编码,我使用的是Python 2.7,所以我的代码如下所示。这对我有用!

# Python2.x --> raw_input
# Python3.x --> input

def option6():
    print("\n")
    print("----------------HEXADECIMAL-DENARY-----------------")
    #converts the entered hexadecimal (in base 16) into a integer using the int function
    hexa = str(raw_input("Please Enter a Hexadecimal : "))
    #hexa = str(input("Please Enter a Hexadecimal : ")) 

    if hexa in ('1', '3', '4', '5','6', 'a', 'b','c','d','e', 'f'):
        denary = int(hexa,16)
        print("Your Denary number is : ",denary)
        print("\n")
        print("===================================================")
        menu= raw_input("Would You Like To Return To The Selection Menu? (Y/N) :")  or 'Y' # default yes
        #menu= input("Would You Like To Return To The Selection Menu? (Y/N) :")  or 'Y' # default yes
        print 'menu-->', menu
        if menu == "Y":
            return

        elif menu == "N":
            print("\n")
            print("==================================")
            print("You Denary number is: ")
            print(denary)
            print("Thank You For Your Time!")

    else:
        print("Not In Range")
        option6()


if __name__ == '__main__':
    option6()