【发布时间】:2016-01-07 23:10:46
【问题描述】:
我正在用 Python 制作凯撒密码。我创建了一个函数来返回用户想要加密的消息。然后我想对密码密钥做同样的事情。我希望函数只返回介于 1 到 26 之间的键,因为这是字母表的大小。它有效,但是当我故意输入一个大于 26 的数字时,输入一个介于 1 和 26 之间的数字;它显然返回“无”。这是我第一次使用递归。
def getKey():
print("Enter the key you want to use to decrypt/encrypt the message")
key = int(input()) # key input
while True:
if key >= 1 and key <= 26: #checking if key is in between range
return key #giving back the key
else: # this should run whenever the input is invalid
print ("The key must be inbetween 1 and 26")
break # to stop the loop
getKey() # Recursion, to restart the function
key = getKey()
print(key) # this prints 'None'
钥匙怎么了?去哪儿了!?
【问题讨论】:
-
您应该使用
return语句返回getKey的结果。 -
@thefourtheye 喜欢
return getKey()?那还会重启功能吗? -
@user3124306 是的,会的。
标签: python function recursion input caesar-cipher