py_whisper_cipher · Python
▶ Aprender py_whisper_cipher (Python) paso a paso · explicación de py_whisper_cipher
Código línea a línea
Tres columnas: el código, el trozo del subject o del main que obliga a escribir esa línea, y el por qué.
py_whisper_cipher.py
| Código | Subject | Por qué |
|---|---|---|
def whisper_cipher(text: str, shift: int) -> str: | def whisper_cipher(text: str, shift: int) -> str: | Firma del subject. |
out = "" | creates a Caesar cipher | Acumulador. |
for ch in text: | Carácter a carácter. | |
if ch.isupper(): | shifting letters in a string by a given amount | Mayúscula: desplazo dentro de A..Z. |
out += chr((ord(ch) - ord("A") + shift) % 26 + ord("A")) | whisper_cipher("xyz", 3) => "abc" | Posición en el alfabeto (0..25), sumo el desplazamiento, % 26 para dar la vuelta, y de vuelta a carácter. En Python % con negativos devuelve positivo: -3 % 26 == 23, así el shift negativo funciona solo. |
elif ch.islower(): | The shift can be negative (shift left). | Minúscula: lo mismo sobre a..z. |
out += chr((ord(ch) - ord("a") + shift) % 26 + ord("a")) | Misma fórmula con base a. | |
else: | Non-alphabetic characters should remain unchanged. | Dígitos, espacios, signos. |
out += ch | Tal cual. | |
return out | Cifrado. |