【发布时间】:2018-01-10 01:40:18
【问题描述】:
我正在进行一个实验项目(创建一个基本的谜机机制),并且在重新分配变量时遇到了问题。我有一个“检查”功能,用于检查以确保用户输入的值是 1 到 26 之间的数字,如果不是,它会再次调用输入函数,要求输入新值。如果我输入 1 到 26 之间的数字(例如:4),一切正常,但是,如果我输入 29 或“qwerty”,它就会开始混乱。它再次调用输入函数(如预期的那样),如果我要输入 4 作为值,则变量被分配为“无”。
我该如何解决这个问题?
工作时的 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)
【问题讨论】:
-
解决您在此处询问的问题后,您可能需要前往Code Review 获取有关构建代码的一般提示。
标签: python python-3.x