任何人可以解释这一段代码是如何知道的整数值“移位-VAL”,因此它减去它从字符的ASCII值定义的函数具有两个参数
alpha=['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
def encodeMessage(message,shift_val):
encodedMessage = ""
l = len(alpha)
length = len(message)
for i in range(0,length):
# ord returns ASCII value of character, we add shift_val to it and
subtract ASCII value of 'A'
x = ord(message[i])+shift_val- ord('A')
# x could exceed 26, we need to cycle back hence mod 26 is used.
x = x % 26
# add xth index alphabet to encoded message
encodedMessage += alpha[x]
# return encodedMessage
return encodedMessage
def main():
# message will be a string
message = ""
UserInput = input("Enter maximum 10 upper-case letters in one line to store: ")
lengthAlpha= len(alpha)
while not UserInput.isalpha() or len(UserInput) > 10 : # message is not acceptable in case it's greater than ten or it isn't a letter
print (" No special characters numbers are allowed (maximum 10 letters) ")
UserInput = input("Enter maximum 10 upper-case letters in one line to store: ")
else:
message =UserInput
message = [element.upper() for element in message]
move = int(input("How far do you wish to shift?: "))
print('The encoded message is',encodeMessage(message, move))
main()
该代码包含一个缩进错误(我假设'return'应该在函数体内部),但它看起来像'shift_val'只是在调用函数时传入函数。这是你问的吗? – Chris
你是对的,回报应该在功能体内。 ord(message [i])获取消息中每个字符的ASCII值,ord('A')对alpha列表做同样的事情。什么是从它被减去的数值被定义为shift_val?对不起,如果问题听起来不好。 –
从ord(message [i])中减去的值是作为'shift_val'传递给函数的任何值。推测这是一些数字值。但是根据你提供的内容,根本没有办法回答这个问题。也许一个数字被传入,也许是一个字符串,也许是一个任意的对象,也许是一个列表或字典,也许是'None'。你需要告诉我们这是如何被调用的。 – Chris