This is a 100 Days challenge to learn a new language (Python). 100 Days of Code - The Complete Python Pro Bootcamp
I will post some notes to motivate myself to finish this challenge.
Function parameters and arguments
Ex:
  # Define a function with some parameters
  # something is called 'Parameter'
  # something is a name of data which has been passing to this function,
  # then we can use this name inside this function as an reference
  def my_function(something):
      print(f"this is {something}")
  # Call a function and pass an argument
  # 123 is called 'Argument'
  # 123 is a actual value of the date we are passing to
  my_function(123)
Result:
  this is 123
Positional V.S. Keyword Argument
Ex:
  # a custom func
  def my_func(name, age):
      print(f"Hello {name}. you are {age} years old")
  # positional argument
  # order matters
  my_func("frank", 5)
  # keyword argument
  # order does not matters
  my_func(age=5, name="frank")
Result:
  Hello frank. you are 5 years old
  Hello frank. you are 5 years old
Challenge - Caesar Cipher
What is it? Reference
Ex:
  # Caesar Cipher
  # Example
  # plain_text = "hello"
  # shift = 5
  # cipher_text = "mjqqt"
  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']
  direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
  text = input("Type your message:\n").lower()
  shift = int(input("Type the shift number:\n"))
  def caesar(direction, text, shift):
      # Define a variable for returning
      result_str = ""
      # Reduce the shift number
      # For example, if shift is 26, then the cipher text and 
      # the raw text are the same
      shift = shift % len(alphabet)
      if direction == 'decode':
          shift *= -1
      # Loop through all letters in text
      for letter in text:
          # Calculate the new index
          new_index = alphabet.index(letter)+ shift
          if new_index <= -1:
              # Ex: index -1 => index 25
              new_index += len(alphabet)
          elif new_index >= len(alphabet):
              # Ex: index 26 => index 0
              new_index -= len(alphabet)
          # Concatenate the string from the encoded letter
          result_str += alphabet[new_index]
      print(f"Here's the {direction} result: {result_str}")
  # Call a funtion to process caesar cipher
  caesar(direction, text, shift)
Result:
  Type 'encode' to encrypt, type 'decode' to decrypt:
  encode
  Type your message:
  hello
  Type the shift number:
  5
  Here's the encode result: mjqqt
  Type 'encode' to encrypt, type 'decode' to decrypt:
  decode
  Type your message:
  mjqqt
  Type the shift number:
  5
  Here's the decode result: hello
No comments:
Post a Comment