Search code examples
pythonpython-3.xcaesar-cipher

Defining a function with two parameters


Can anybody explain how this piece of code knows the integer value of "shift-val" so it subtracts it from the ASCII value of character

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()

Solution

  • The user is asked for an amount to "shift". This value is stored in a variable called move as an integer:

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

    This value is passed into encode_message(), where it is bound to the shift_val parameter:

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

    encodeMessage() knows the value of shift_val because it gets passed into the function as an argument. In another context shift_val could have any other value; it depends entirely on how the function is called.