Python - 没有执行其他条件

时间:2017-03-06 09:59:09

标签: python

请检查下面的代码,其他条件匹配(测试数据为“k”),但不执行其中的语句,而是给出错误,如 -

NameError: name "k" is not defined.

同时如果我给8或9,它同时没有显示上述错误也没有执行else语句,只是再次显示主菜单

from math import sqrt
def addition(firstNum,secondNum):
    total = firstNum+secondNum
    return total

def substraction(firstNum,secondNum):
    total = firstNum-secondNum
    return total

def multiplication(firstNum,secondNum):
    total = firstNum*secondNum
    return total

def division(firstNum,secondNum):
    total = firstNum/secondNum
    return total

def root(firstNum):
    total = (firstNum*firstNum)
    return total

menu={}
menu[" "] = "          --------PYTHON CALCULATOR-------            "
menu["."] = "~~Main Menu~~"
menu["1"] = "Addition"
menu["2"] = "Substraction"
menu["3"] = "Multiplication"
menu["4"] = "Division"
menu["5"] = "Square"
menu["6"] = "Root"
menu["7"] = "Exit\n"

while True:
    options = menu.keys()
    options.sort()
    for entry in options:
        print entry, menu[entry]

    selection = input("Please select your correct option: ")

    if selection   == 1:
        firstNum=input ("\nPlease enter first number : ")
        secondNum=input("Please enter Second number: ")

        print "Answer is " , addition(firstNum,secondNum)
        print "--------------------------------------------------------\n\n"
    elif selection == 2:
        firstNum=input ("\nPlease enter first number : ")
        secondNum=input("Please enter Second number: ")
        print "Answer is " ,substraction(firstNum,secondNum)
        print "--------------------------------------------------------\n\n"
    elif selection == 3:
        firstNum=input ("\nPlease enter first number : ")
        secondNum=input("Please enter Second number: ")
        print "Answer is ",multiplication(firstNum,secondNum)
        print "--------------------------------------------------------\n\n"
    elif selection == 4:
        firstNum=input ("\nPlease enter first number : ")
        secondNum=input("Please enter Second number: ")
        print "Answer is " ,division(firstNum,secondNum)
        print "--------------------------------------------------------\n\n"
    elif selection == 5:
        firstNum=input ("\nPlease enter first number : ")
        print "Answer is " ,sqrt(firstNum)
        print "--------------------------------------------------------\n\n"
    elif selection == 6:
        firstNum=input ("\nPlease enter first number : ")
        print "Answer is " ,root(firstNum)
        print "--------------------------------------------------------\n\n"
    elif selection == 7:
        break
    else:
        "Invalid option keyed in..."

1 个答案:

答案 0 :(得分:1)

使用raw_input代替inputHere's whyraw_input返回用户输入的string,您应该使用以下代码转换为int

firstnum = int(raw_input('...'))