使用两个参数定义函数

时间:2017-04-23 03:53:13

标签: python python-3.x caesar-cipher

任何人都可以解释这段代码如何知道“shift-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 个答案:

答案 0 :(得分:0)

要求用户输入&#34; shift&#34;。该值作为整数存储在名为 <!DOCTYPE html> <html> <head> <title>Funky Munky Arcade</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <nav class="navbar navbar-default navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <a href="/index.html" class="navbar-left"><img src="FMA_Logo.png" class="logo"></a> </div> <ul class="nav navbar-nav"> <li><a href="#">Home</a></li> <li><a href="#">Parties</a></li> <li><a href="#">Contact</a></li> </ul> </div> </nav> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> </body> </html> 的变量中:

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可以有任何其他价值;它完全取决于函数的调用方式。