48 lines
1.4 KiB
Python
48 lines
1.4 KiB
Python
|
|
def cifra(messaggio, shift):
|
||
|
|
"""
|
||
|
|
Cifra il messaggio usando il cifrario di Cesare con lo spostamento dato.
|
||
|
|
- Lettere minuscole rimangono minuscole
|
||
|
|
- Lettere maiuscole rimangono maiuscole
|
||
|
|
- Caratteri non alfabetici (spazi, numeri, punteggiatura) rimangono invariati
|
||
|
|
"""
|
||
|
|
risultato = ""
|
||
|
|
|
||
|
|
for c in messaggio:
|
||
|
|
if c.islower():
|
||
|
|
base = ord('a')
|
||
|
|
codice = ord(c)
|
||
|
|
nuovo_codice = (codice - base + shift) % 26 + base
|
||
|
|
cifrato = chr(nuovo_codice)
|
||
|
|
calcolo = f"({codice} - {base} + {shift}) % 26 + {base} = {nuovo_codice}"
|
||
|
|
|
||
|
|
elif c.isupper():
|
||
|
|
base = ord('A')
|
||
|
|
codice = ord(c)
|
||
|
|
nuovo_codice = (codice - base + shift) % 26 + base
|
||
|
|
cifrato = chr(nuovo_codice)
|
||
|
|
calcolo = f"({codice} - {base} + {shift}) % 26 + {base} = {nuovo_codice}"
|
||
|
|
|
||
|
|
else:
|
||
|
|
cifrato = c
|
||
|
|
|
||
|
|
risultato += cifrato
|
||
|
|
|
||
|
|
return risultato
|
||
|
|
|
||
|
|
|
||
|
|
|
||
|
|
messaggio = input("Inserire un messaggio da cifrare: ")
|
||
|
|
|
||
|
|
shift = 0
|
||
|
|
while shift < 1 or shift > 25:
|
||
|
|
try:
|
||
|
|
shift = int(input("Inserire il valore di spostamento (1-25): "))
|
||
|
|
if shift < 1 or shift > 25:
|
||
|
|
print("Valore fuori intervallo. Inserire un numero tra 1 e 25.")
|
||
|
|
except ValueError:
|
||
|
|
print("Input non valido. Inserire un numero intero.")
|
||
|
|
|
||
|
|
testo_cifrato = cifra(messaggio, shift)
|
||
|
|
|
||
|
|
print(f"Messaggio cifrato: {testo_cifrato}")
|