Udemy - 100 Days of Code: The Complete Python Pro Bootcamp
Day 8 - Beginner - Function Parameters & Caesar Cipher 凯撒密码
61. Functions with Inputs
# Defining a Function
def my_function(name): # Parameter 形参
print(f"Hello {name}")
print(f"How do you do {name}?")
# Calling a Function
my_function("Tommy") # Argument 实参
62. Positional vs Keyword Arguments
# Multiple Inputs
def my_function(name, location):
print(f"Hello {name}")
print(f"What is it like in {location}")
# Positional Arguments 位置参数
my_function("Jack Bauer", "Nowhere")
# Keyword Arguments 关键字参数
my_function(location="London", name="Angela")
63. Caesar Cipher 1 - Encryption
def encrypt(original_text, shift_amount):
output_text = ""
for letter in original_text:
shifted_position = alphabet.index(letter) + shift_amount
shifted_position %= len(alphabet)
output_text += alphabet[shifted_position]
print(f"Here is the encoded result: {output_text}")
64. Caesar Cipher 2 - Decryption
def decrypt(original_text, shift_amount):
output_text = ""
for letter in original_text:
shifted_position = alphabet.index(letter) - shift_amount
shifted_position %= len(alphabet)
output_text += alphabet[shifted_position]
print(f"Here is the decoded result: {output_text}")
# Combine encrypt() and decrypt() functions
def caesar(original_text, shift_amount, encode_or_decode):
output_text = ""
if encode_or_decode == "decode":
shift_amount *= -1
for letter in original_text:
shifted_position = alphabet.index(letter) + shift_amount
shifted_position %= len(alphabet)
output_text += alphabet[shifted_position]
print(f"Here is the {encode_or_decode}d result: {output_text}")
65. Caesar Cipher 3 - Reorganizing our Code
alphabet = ['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 caesar(original_text, shift_amount, encode_or_decode):
output_text = ""
if encode_or_decode == "decode":
shift_amount *= -1
for letter in original_text:
if letter not in alphabet:
output_text += letter
else:
shifted_position = alphabet.index(letter) + shift_amount
shifted_position %= len(alphabet)
output_text += alphabet[shifted_position]
print(f"Here is the {encode_or_decode}d result: {output_text}")
should_continue = True
while should_continue:
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n").lower()
text = input("Type your message:\n").lower()
shift = int(input("Type the shift number:\n"))
caesar(original_text=text, shift_amount=shift, encode_or_decode=direction)
restart = input("Type 'yes' if you want to go again. Otherwise, type 'no'.\n").lower()
if restart == "no":
should_continue = False
print("Goodbye")
818

被折叠的 条评论
为什么被折叠?



