首页 > 解决方案 > 如何在 Python 中编写正确的 if 语句?

问题描述

我用 Python 制作了这个简单的 Caesar Cipher 程序,它对单词进行编码和解码,我要做的就是为用户写一个 if 语句,如果他们写了一个错误的单词(除了“解码”和“编码”之外的任何东西)并告诉他们再试一次,我一直在尝试并做了很多研究,但找不到任何帮助。当然还有很多其他方法可以做到这一点,但我想将其添加到我的特定代码中,而不是更改代码本身,我不知道如何..

任何帮助,将不胜感激..

这是我的代码:

#from art import logo
#print(logo)

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', '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']

def caesar(start_text, shift_amount, cipher_direction):
  end_text = ""

  if cipher_direction == "decode":
    shift_amount *= -1
  for char in start_text:
    if char in alphabet:
        position = alphabet.index(char)
        new_position = position + shift_amount
        end_text += alphabet[new_position]
    else:
        end_text += char
  
    
  print(f"\nHere's the {cipher_direction}d result: {end_text}")



should_continue = True
while should_continue:
    direction = input("\nType 'encode' to encrypt, type 'decode' to decrypt: ")
    text = input("\nType your message: ").lower()
    shift = int(input("\nType the shift number: "))

    shift = shift % 26
    caesar(start_text=text, shift_amount=shift, cipher_direction=direction)

    result = input("\nType 'yes' if you want to go again, otherwise type 'no': ").lower()
    if result == "no":
        should_continue = False
        print("\nGoodbye!")

标签: python

解决方案


direction = input("\nType 'encode' to encrypt, type 'decode' to decrypt: ").lower()
if direction != "encode" and direction != "decode":
    continue
else:
    text = ...
    ...

推荐阅读