Back to Freecodecamp

Step 49

curriculum/challenges/english/blocks/learn-string-manipulation-by-building-a-cipher/6553a572f7a65718f1e42e18.md

latest2.0 KB
Original Source

--description--

A function is essentially a reusable block of code. You have already met some built-in functions, like print(), find() and len(). But you can also define custom functions like this:

py
def function_name():
    <code>

A function declaration starts with the def keyword followed by the function name — a valid variable name — and a pair of parentheses. The declaration ends with a colon.

Right after your shift variable, declare a function called caesar and indent all the following lines to give your new function a body.

--hints--

You should use the def keyword to declare a new function.

js
assert.match(code, /^def\s+/m)

You should write caesar as the function name after the def keyword. Remember to add a space after def.

js
assert.match(code, /^def\s+caesar/m)

You should add a pair of parentheses after the function name. Don't forget the final colon.

js
assert.match(code, /^def\s+caesar\s*\(\s*\)\s*:/m)

You should indent all the lines after shift = 3 so that they become your new function body.

js
({ test: () => {
    const commentless_code = __helpers.python.removeComments(code);
    const {def} = __helpers.python.getDef(commentless_code, "caesar");    
    const replacement = def.replace(/print\s*\(\s*("|')plain\stext:\1\s*,\s*text\s*\)\s*print\s*\(\s*("|')encrypted\stext:\2\s*,\s*encrypted_text\s*\)/, "return encrypted_text")
    const py_code = `
text = "Hello Zaira"
shift = 3
${replacement}
caesar()
`
    const out = runPython(py_code, {});
    assert.equal(out, "khoor cdlud");
  }
})

--seed--

--seed-contents--

py
--fcc-editable-region--
text = 'Hello Zaira'
shift = 3

alphabet = 'abcdefghijklmnopqrstuvwxyz'
encrypted_text = ''

for char in text.lower():
    if char == ' ':
        encrypted_text += char
    else:
        index = alphabet.find(char)
        new_index = (index + shift) % len(alphabet)
        encrypted_text += alphabet[new_index]
print('plain text:', text)
print('encrypted text:', encrypted_text)
--fcc-editable-region--