[英]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 谁能解释一下这段代码如何知道“ 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()
The user is asked for an amount to "shift". 询问用户要“转移”的金额。 This value is stored in a variable called
move
as an integer: 此值以整数形式存储在名为
move
的变量中:
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: 此值传递到
encode_message()
,在此绑定到shift_val
参数:
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. encodeMessage()
知道的价值shift_val
因为它被传递给函数作为参数。 In another context shift_val
could have any other value; 在另一个上下文中,
shift_val
可以具有任何其他值; it depends entirely on how the function is called. 这完全取决于函数的调用方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.