我正在研究一个实验项目(创建一个基本的谜机器机制),并且在重新分配变量时遇到了一个问题。我有一个“检查”函数,用于检查用户输入的值是1到26之间的数值,如果不是,它会再次调用输入函数,要求一个新值。如果我输入一个介于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)
后您解决问这里的问题,你可能要头以上[ codereview.SE]来获得关于构造代码的一些常规技巧。 –