我正在研究一個實驗項目(創建一個基本的謎機器機制),並且在重新分配變量時遇到了一個問題。我有一個「檢查」函數,用於檢查用戶輸入的值是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]來獲得關於構造代碼的一些常規技巧。 –