2017-04-23 111 views
0

任何人可以解释这一段代码是如何知道的整数值“移位-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() 
+1

该代码包含一个缩进错误(我假设'return'应该在函数体内部),但它看起来像'shift_val'只是在调用函数时传入函数。这是你问的吗? – Chris

+0

你是对的,回报应该在功能体内。 ord(message [i])获取消息中每个字符的ASCII值,ord('A')对alpha列表做同样的事情。什么是从它被减去的数值被定义为shift_val?对不起,如果问题听起来不好。 –

+0

从ord(message [i])中减去的值是作为'shift_val'传递给函数的任何值。推测这是一些数字值。但是根据你提供的内容,根本没有办法回答这个问题。也许一个数字被传入,也许是一个字符串,也许是一个任意的对象,也许是一个列表或字典,也许是'None'。你需要告诉我们这是如何被调用的。 – Chris

回答

0

用户被要求用于相当于“转移”。该值被存储在称为move为整数变量:

move = int(input("How far do you wish to shift?: ")) 

该值被传递到encode_message(),在那里它被绑定到shift_val参数:

print('The encoded message is',encodeMessage(message, move)) 

encodeMessage()知道的shift_val,因为该值它作为参数传入函数。在另一种情况下,shift_val可以具有任何其他值;它完全取决于函数的调用方式。

+0

谢谢@Chris!你在说基本上,shift-val从用户输入中获得它的价值,所以函数也可以被写为; def encodeMessage(message,move): x = ord(message [i])+ move-ord('A') –

+0

@EmreÇakır,只有'move'设置为'int(input(“多远你希望转移?:“))'在函数的范围内。它仍然需要通过,例如通过调用'encodeMessage(message,move)',就像你现在一样。函数声明中的参数'move'和函数外部的变量'move'没有关系;当您调用该变量时将该变量传递给该函数将其值绑定到该参数。 – Chris

相关问题