-1

我只是好奇,如何确保我的 input1 不等于 input2?如果是这种情况,那么会提示错误吗?我已经在我的代码中使用了 def 语句来检查输入的输入是字符串而不是数值,而且我认为我实际上不能将它结合起来,所以 def 语句可以做这两件事..有什么办法吗?

4

1 回答 1

2

确保输入有效的功能:

def isvalid(*values):
    for value in values:
        #check a value is invalid 
        if not value in ['pound', 'euro', 'dollar', 'yen']: #etc...
            return False
    return True

主循环:

def get_input():
    a = raw_input("A: ")
    b = raw_input("B: ")
    while (not isvalid(a,b) or a != b):
        print("The inputs were not identical! Please try again.")
        a = raw_input("A: ")
        b = raw_input("B: ") 
    print("{0} = {1}".format(a,b))

get_input()

或者,您可以只有一个功能来实现相同的功能:

def get_input():
    valid_values = ['pound', 'euro', 'dollar', 'yen'] #etc...
    a = raw_input("A: ")
    b = raw_input("B: ")
    while (not (a in valid_values and b in valid_values) or a != b):
        print("The inputs were not valid! Please try again")
        a = raw_input("A: ")
        b = raw_input("B: ") 
    print("{0} = {1}".format(a,b))

注:这not (a in valid_values and b in valid_values)德摩根定律的一个例子。并且可以重写为not (a in valid_values) or not (b in valid_values).

产生,以下为例:

A: pound
B: orange
The inputs were not valid! Please try again
A: pound
B: euro
The inputs were not valid! Please try again
A: pound
B: pound
pound = pound
>>> 

要访问在外部输入的值,get_input您可以这样做

def get_input():
        valid_values = ['pound', 'euro', 'dollar', 'yen'] #etc...
        a = raw_input("A: ")
        b = raw_input("B: ")
        while (not (a in valid_values and b in valid_values) or a != b):
            print("The inputs were not valid! Please try again")
            a = raw_input("A: ")
            b = raw_input("B: ") 
        print("{0} = {1}".format(a,b))
            return a,b #THIS WAS THE CHANGE

然后像这样调用它:

print("CALLING get_input")
A,B = get_input()
print("CALLED get_input")
#we can now access the result outside of get_input
print(A)
print(B)

将产生:

>>> 
CALLING get_input
A: pound
B: pound
pound = pound
CALLED get_input
pound
pound

在 Python 3.x 中使用input而不是raw_input

于 2013-04-30T00:20:33.963 回答