'while' l oop ведет себя не так, как ожидалось - PullRequest
0 голосов
/ 13 января 2020

Справочная информация:

Я создал программу, которая принимает текстовый ввод, применяет шифрование (простой шифр) и сохраняет вывод в список - при желании. Сообщения также могут быть расшифрованы.

Программа перемещается через меню параметров: 1. Зашифровать сообщение 2. Просмотреть зашифрованные сообщения 3. Расшифровать сообщение

Чтобы разрешить всем разделам программы доступ к тому же списку (переменной) сохраненных сообщений, я написал его в классе. Внутри класса существуют определения, вызывающие этот список.

На данный момент записан только бит "зашифровать сообщение".

Проблема:

Процесс принятия решения пользователем осуществляется с двумя вариантами Y / N. Однако эти варианты не работают - даже если пользователь вводит «N» - моя программа считает, что они набрали «Y» в обоих случаях.

def encrypt():
    def save_cip():#This function allows the user to save the ciphered message to the ciphered_messages if they choose
        choosing = True
        while choosing:
            save_choice = input("Would you like to save your Ciphered message? (Y/N)\n")
            if save_choice == "Y" or "y":
                print("You chose yes")
                cct.ciphered_messages.append(' '.join(["Message", str(len(cct.ciphered_messages)), ":", cipher]))
                choosing = False
            elif save_choice == "N" or "n":
                print("You chose no")
                choosing = False
                continue
            else:
                print("That was not a valid entry, please enter Y or N only")
                continue

Я думаю, что проблема лежит в области видимости, и что почему-то на одну и ту же переменную не ссылаются при установке и чтении Y или N. Я шел вверх и вниз по одному и тому же коду около 3 часов и до сих пор ничего, объявляя все переменные во многих разных местах без удачи, поэтому любые советы очень приветствуется.

Полный исполняемый код:

class cct:

print("Welcome to the CaeserCipher tool v1.0")
menu_state = "main" #This is used to record what state the program is in
unciphered_messages = [] #Decrypted messages are saved here
ciphered_messages = [] #Encrypted messages are saved here

def menu(): #This is the main menu interface
    while cct.menu_state == "main": #This while 
        cct.menu_state = input("What would you like to do? \n 1: Encrypt a Message \n 2: View Encrypted Messages \n 3: Decrypt a message\n")
        if cct.menu_state == "1":
            cct.encrypt()
        elif cct.menu_state == "2":
            cct.view()
        elif cct.menu_state == "3":
            cct.decrypt()
        elif cct.menu_state == "main":
            print("\n\nWelcome back to the menu!\n\n")
        else:
            print("You did not enter a valid choice. Please enter a number between 1 and 3.\n")
            cct.menu_state = "make_choice"
        continue

def encrypt():
    def save_cip():#This function allows the user to save the ciphered message to the ciphered_messages if they choose
        choosing = True
        while choosing:
            save_choice = input("Would you like to save your Ciphered message? (Y/N)\n")
            if save_choice == "Y" or "y":
                print("You chose yes")
                cct.ciphered_messages.append(' '.join(["Message", str(len(cct.ciphered_messages)), ":", cipher]))
                choosing = False
            elif save_choice == "N" or "n":
                print("You chose no")
                choosing = False
                continue
            else:
                print("That was not a valid entry, please enter Y or N only")
                continue

    #This while loop continually takes messages, gives the option of saving, and asks if you want to cipher another
    while cct.menu_state == "1":   
        text = input("Enter your message: ") #Enter the message you wish to cipher
        cipher = '' #Create a string for the cipher
        for char in text: #This for sub-loop will increment each character by 1. e.g. A -> B, T -> U, Z -> A
            if not char.isalpha():
                continue
            char = char.upper()
            code = ord(char) + 1
            if code > ord('Z'):
                code = ord('A')
            cipher += chr(code)
        print(' '.join(["Your ciphered message is:", cipher]))
        save_cip()
        print(cct.ciphered_messages)
        #This sub-while loop is reponsible for checking if you want to cipher another message
        #and making sure the user has made a valid choice
        choosing_another = True
        while choosing_another == True:
            choice_variable = input(' '.join(["You have", str(len(cct.ciphered_messages)), "saved messages \n", "Would you like to Cipher another? (Y/N)\n"]))
            if choice_variable == "Y" or "y":
                print("You chose yes")
                choosing_another = False
            elif choice_variable == "N" or "n":
                print("You chose no")
                cct.menu_state = "main"
                choosing_another = False
            else:
                choice_variable = input("That was not a valid entry, please enter Y or N only: \n")
                continue
    return


def view():
#TO BE CODED
    return

def decrypt():
    #TO BE CODED
    return

cct.menu ()

Ответы [ 2 ]

0 голосов
/ 13 января 2020

Не python программист, но я не думаю, что python допускает "подразумеваемую" тему для оператора или
-> IF save_choice == "Y" ИЛИ save_choice == "y":

0 голосов
/ 13 января 2020

Это всегда верно:

if save_choice == "Y" or "y":

, потому что это интерпретируется как:

if (condition) or (condition):

1-е условие (save_choice == "Y")

2-е условие - это просто ("y"), которое python интерпретируется как 'True'

Таким образом, все условие всегда True.

U, вероятно, означает:

if save_choice == "Y" or save_choice == "y":

Или лучше:

if save_choice.lower() == "y":
...