我只是好奇,如何确保我的input1不等于input2?如果是这种情况,那么提示错误?我已经在我的代码中使用def语句来检查输入的输入是字符串而不是数值,我不认为我实际上可以将它组合起来所以def语句可以做两件事..有什么办法吗?
答案 0 :(得分: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)
是De Morgan's Law的情况。并且可以重写为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