我正在做一个实验项目(创建一个基本的enigma机器机制),在重新分配变量时遇到了一个问题。我有一个“check”函数,它检查以确保用户输入的值是1到26之间的数字,如果不是,它会再次调用input函数,请求一个新值。如果我输入一个介于1和26之间的数字(例如:4),一切都会正常工作,但是如果我输入29或“qwerty”,它就会开始出错。它再次调用输入函数(如预期的那样),如果输入4作为值,变量将被指定为“None”。你知道吗
我怎样才能解决这个问题?你知道吗
工作时的CLI输出(例如:输入4):
What is the message you would like to encrypt?as
For the next 3 questions, please input ONLY a number from 1 to 26
What is the first key value?4
4
失败时的CLI输出(例如:输入28然后输入4):
What is the message you would like to encrypt?asd
For the next 3 questions, please input ONLY a number from 1 to 26
What is the first key value?28
You must input a number between 1 and 26!
What is the first key value?4
None
代码:
class Input:
def message():
msg = input("What is the message you would like to encrypt?")
msg = msg.upper()
print("\n For the next 3 questions, please input ONLY a number from 1 to 26")
def check(input):
try:
if int(input) < 1 or int(input) > 26:
return False
else:
return True
except:
return False
def getKey(keyNum):
word = ""
if keyNum == 1:
word = "first"
elif keyNum == 2:
word = "second"
else:
word = "third"
s = input("What is the {} key value?".format(word))
chk = Input.check(s)
if chk:
return(s)
else:
print("You must input a number between 1 and 26!")
Input.getKey(1)
inp = Input
inp.message()
s1 = inp.getKey(1)
print(s1)
您已经创建了类名
Input
,因此它的类函数中应该有第一个参数self,而且在从函数内部调用同一个函数时,我们将通过self.name
函数调用它,这样它就不会为其他变量调用其他函数,而是为当前变量调用其他函数。一个小错误是调用
Input.getKey(1)
,它应该正确地像self.getKey(keyNum)
一样提供当前密钥。你知道吗在类变量here中调用成员函数的正确方法
看到它工作了吗here
在您的代码中:
当
chk
是“truthy”时,也就是说,当if chk:
成功时,返回s
。你知道吗但是当
else:
运行时,不会返回任何内容。相反,您将递归到getKey(1)
(这是错误的-您应该使用参数,以防它是2或3)。你知道吗现在,对
getKey(1)
的递归调用将返回一个值。但是你忽略了这个值并且不返回。你知道吗由于不在该分支中返回,因此“跌入”函数的末尾,Python的默认机制在这里起作用:如果函数不返回任何值,Python会自动提供一个
None
作为结果。你知道吗这就是你在
else:
案件中得到的。你知道吗问题来自
getKey()
函数:如果对
Input.check(s)
的第一个调用返回True
,则getKey()
返回输入的值。但是如果第一个调用返回False
,那么getKey()
不会返回任何内容。它会再次请求输入,您可以看到,但它从不将输入传递回需要它的代码。您需要做的是向else
块添加一个适当的return
语句,以便返回来自对getKey()
的递归调用的值。你知道吗相关问题 更多 >
编程相关推荐