【问题标题】:How can I write an ASCII Caesar cipher in Python如何在 Python 中编写 ASCII 凯撒密码
【发布时间】:2020-10-23 16:53:53
【问题描述】:

我是一个完整的初学者,我的任务是创建一段代码

  1. 要求用户输入字符串
  2. 要求用户输入一个介于 1 和 25 之间的值,该值可用作 ascii 移位器
  3. 根据他们希望以 ascii 形式移动的值输出他们的字符串输入

我知道这是一个很长的尝试,但这是我迄今为止的代码,任何帮助或正确方向的指示将不胜感激。

# Description: 
# A program to read in a single word message
# the input is modified by code and the Encoded
# word is displayed.

# NAMED_CONSTANTS
SMALLEST_SHIFT_NUMBER = 1
LARGEST_SHIFT_NUMBER = 25
ASSCII_CODE_NINETY = 90
ASSCII_CODE_TWENTY_SIX = 26


# DECLARE the Program Variables

# Set the initial SHIFT number to add on as zero
# This number is ADDED to a letter's ASCII code value
# Default initial value is: 0
code_number_add_on = 0

# A capital letter entered by the user
# Default initial value is: A
capital_letter = "A"

# The ASCII CODE for the new letter that replace
# a user's capital letter
# Default initial value is: 0
ascii_code_new_letter = 0

# The new LETTER that replace a user's capital letter
# Default initial value is: A
new_letter = "A"

# function get_encoding_number returns an int
# value after input validation for 
# a value in the range:
def get_encoding_number():

# Set a flag for input validation
# Default initial value is: False

    valid_shift_number_entered = False

    # While the flag is False - prompt for and process user input
    while valid_shift_number_entered == False:

        # Prompt for a valid number
        get_encoding_number = int(input("Enter a value on the range 1 to 25: "))

    # Test the user input value
    if get_encoding_number >= SMALLEST_SHIFT_NUMBER and get_encoding_number <= LARGEST_SHIFT_NUMBER:

        # Valid input - update the flag to True
        valid_shift_number_entered = True

    else:

        # Invalid input - display an error message
        print("Error: unacceptable value.")

    # END if statement

# END while loop
    return 2

# END function first


# function string_to_be_encoded returns a String
# value. The function prints a user prompt and
# returns the input without input validation  
def function_to_get_user_word_for_encoding():

    string_to_be_encoded = input("Enter a word in CAPITAL letters to be encoded. Press ENTER. ")
    return string_to_be_encoded

# END function second


# a helper function encode_one_letter
# returns an
# encoded letter. 
#  
def encode_one_letter( the_letter, encode_number ):

    # code from alphabet_08.py
    # approx lines 63 to 78

    # Use the function ord to determine the
    # ASCII code for the letter entered by the user
    ascii_code_for_user_letter = ord( the_letter )

    # Now the SHIFT value must be added
    ascii_code_new_letter = ascii_code_for_user_letter + encode_number

    # if the calculated value is greater than 90 then
    # subtract 26 to create a valid capital letter value
    if ascii_code_new_letter > ASSCII_CODE_NINETY:
        ascii_code_new_letter = ascii_code_new_letter - ASSCII_CODE_TWENTY_SIX
    # END if

    # Use the function ord to determine the ASCII code for
    # the new letter after the SHIFT value has been added.
    new_letter = chr(ascii_code_new_letter)

    return new_letter

# END function encode_one_letter


# function           returns a String
# value. The function has two parameters
# a number and a text string. The function
# encodes each letter in the text and returns
# the encoded word as a String.  
def third( number_for_code, word ):

    # a local variable to hold an encoded letter
    encoded_letter = ""
    # a local variable to hold the encoded word
    encoded_word = ""

    # a for loop to encode each letter in the 
    for letter in word:
    
    # encode the current letter
        encoded_letter = encode_one_letter( letter , number_for_code )

        # add the letter to the encoded word using the method append()
        encoded_word = encoded_word + encoded_letter

        # reset the encoded_letter to an empty string
        encoded_letter = ""     

    # END for loop


    # return the encoded word
    return encoded_word

# END function third


# function main prints User inputs
def main():

    # print a welcome message
    print("\n\tWelcome to program outline_03.py")

    # read a valid number input
    # into a local variable
    # ??? = get_encoding_number()

    # read a text input
    # into a local variable
    # ??? = second()

    # combine the user inputs
    # into a third local variable
    v3 = third( 2, "PAUL" )

    print("\n\tHere is the encoded word:", v3 )

    print("\n\tProgram secret_codes.py ends.")  

# END function main


# call function main
main()

【问题讨论】:

  • 这看起来像是一个家庭作业问题,你应该自己解决它

标签: python python-3.x ascii caesar-cipher


【解决方案1】:

您的代码有很多神奇的数字、函数名称(例如 third(...))并不能告诉您该函数的作用,还有大量过时的 cmets 可以解释如果您有更好的变量名开头可以避免解释的内容 - 等等.

让你的生活更轻松,使用 python 给你的东西:

那么你可以这样写:

from string import ascii_lowercase as lc

while True:
    # simply force the input to be lower or upper, no cooperation needed
    text = input ("A message, enter to quit: ").lower()
    if not text:
        break
    try:
        # use try except in case they do not input a number and allow -25 to 25
        # to enable back-converting your text
        shift = int(input("Shift between -25 and 25: "))
        if not (-25 <= shift <= 25):
            raise ValueError()
    except ValueError:
        print("Try again")

    # make the translation dictionary and translate the text 
    tran = str.maketrans(lc, lc[shift:] + lc [:shift])
    print(text.translate(tran),"\n")

获得:

A message, enter to quit: Baker Street23
Shift between -25 and 25: 5
gfpjw xywjjy23

A message, enter to quit: gfpjw xywjjy23
Shift between -25 and 25: -5
baker street23 

【讨论】:

    猜你喜欢
    • 2020-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-13
    • 1970-01-01
    • 2014-03-30
    • 1970-01-01
    相关资源
    最近更新 更多