2013-08-16 2 views
0

Voici le code:Pourquoi mon poste César ne fonctionne-t-il pas correctement?

text = input("What's your text: ") 
shift = int(input("What's your shift: ")) 

def caesar_shift(text, shift): 
    cipher = "" 
    for i in text: 
     if i.isalpha(): 
      stayIn = ord(i) + shift 
      if stayIn > ord('z'): 
       stayIn -= 26 
      lastLetter = chr(stayIn) 
     cipher += lastLetter 

     print("Your ciphertext is: ", cipher) 

    return cipher 

caesar_shift(text, shift) 

Quand je le lance, et par exemple, le test est bonjour monde, et le changement est 1, je reçois:

What's your text: hello world 
What's your shift: 1 
Your ciphertext is: i 
Your ciphertext is: if 
Your ciphertext is: ifm 
Your ciphertext is: ifmm 
Your ciphertext is: ifmmp 
Your ciphertext is: ifmmpp 
Your ciphertext is: ifmmppx 
Your ciphertext is: ifmmppxp 
Your ciphertext is: ifmmppxps 
Your ciphertext is: ifmmppxpsm 
Your ciphertext is: ifmmppxpsme 

Pourquoi? Est-ce que je fais quelque chose de mal, merci d'avance!

Répondre

3

Vous ne

if i.isalpha(): 

mais vous n'avez pas d'autre article pour que si. Cela signifie que vous ajoutez la dernière lettre aussi quand ce n'est pas une lettre. Par conséquent ifmmpp au lieu de ifmmp pour hello.

Ce bit devrait être remplacé par:

if i.isalpha(): 
    stayIn = ord(i) + shift 
    if stayIn > ord('z'): 
     stayIn -= 26 
    lastLetter = chr(stayIn) 
    cipher += lastLetter 
else: 
    cipher += i 

Si vous ne voulez pas le résultat à imprimer une fois pour chaque boucle, déplacer en dehors de la boucle.

+0

Pas de réponse est juste, je me demande pourquoi il l'imprime comme ça, comment puis-je obtenir la dernière réponse? – Samir

+0

@Samir: Non, la réponse est incorrecte, que vous remarquerez si vous la décalez. J'ai mis à jour l'explication pour couvrir votre autre question aussi. –

0

Pour résoudre le problème d'impression, vous avez:

def caesar_shift(text, shift): 
    cipher = "" 
    for i in text: 
     ... 

     print("Your ciphertext is: ", cipher) 

    return cipher 

caesar_shift(text, shift) 

Mais vous devriez avoir

def caesar_shift(text, shift): 
    cipher = "" 
    for i in text: 
     ... 

    print("Your ciphertext is: ", cipher) 

    return cipher 

caesar_shift(text, shift) 

Ou mieux encore

def caesar_shift(text, shift): 
    cipher = "" 
    for i in text: 
     ... 

    return cipher 

print("Your ciphertext is: ", caesar_shift(text, shift)) 
Questions connexes