Код шифрования в функции def для написания на Python - PullRequest
0 голосов
/ 26 апреля 2018

нужна некоторая помощь в следующем коде, поскольку он входит в бесконечный цикл и не проверяет пользовательский ввод: функция get_offset является. Только что отредактированному требуется некоторая помощь с частью шифрования, чтобы быть сделанной в функции, определенной

def get_offset(offset):
    while True:
        value = (offset)
        if value < 1:
            print("")
        if value > 94:
            print("")
    return offset

my_details = display_details()

get_choice = get_menu_choice()

print(my_details)
print(get_choice)

count = 10

while count > 0:

    count -=1

    encrypted = ""

    choice = int(input("What would you like to do [1,2,3,4,5]: "))

    while choice <1 and choice > 5:
        print("Invalid choice, please enter either 1, 2, 3, 4 or 5.")

    if choice == 1:
        string_input = input("Please enter string to encrypt: ")
        input_offset = get_offset(int(input("Please enter offset value (1 to 94): ")))

   **for letter in string_input:
        x = ord(letter)
        encrypted += chr(x + input_offset)
        if x < 32:
            x += 94
        if x > 126:
            x -= 94

    print(encrypted)**

1 Ответ

0 голосов
/ 26 апреля 2018

Вы должны назначить choice новое значение внутри внутреннего цикла while. таким образом, новый ввод учитывается перед повторной итерацией.

это должно сработать:

while choice < 1 and choice > 5:
    choice = int(input("Invalid choice, please enter either 1, 2, 3, 4 or 5."))

Случайный совет: если вы хотите, чтобы набор данных строго совпадал с [1,2,3,4,5], вам следует избегать choice<1 и choice>5. Это делает вашу программу уязвимой для некорректных входных данных, таких как 3.5.

Вместо этого вы должны сделать это:

valid_inputs = [1, 2, 3, 4, 5]

choice = int(input("Pick a number from [1, 2, 3, 4, 5]:"))

while choice not in valid_inputs:
    choice = int(input("Invalid choice, please enter either 1, 2, 3, 4 or 5."))

<rest of stuff here>

Из ваших комментариев я понял, что в get_offset() вы хотите, чтобы пользователь вводил значение в диапазоне от 1 до 94. Если пользователь вводит что-то из этого диапазона, вы хотите задавать вопрос снова и снова. Код ниже должен делать то, что вы хотите:

def get_offset():
   # first, ask for a value.
   offset = int(input("Enter a value between 1 and 94:"))
   while offset < 1 and offset > 94:
      # if the value is invalid, trap user inside this while loop.
      # user will be stuck here (while loop will return true) 
      # until a valid input is received.
      offset = int(input("Invalid input. Please enter a value between 1 and 94:"))
   # if we proceed down here, it means we are over while loop 
   # and it implies that user has given us valid input. return value.
   return offset

Во-вторых, внутри основного цикла while вы можете вызвать get_offset() так:

if choice == 1:
    string_input = input("Please enter string to encrypt: ")
    input_offset = get_offset()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...