2022年5月3日:使用 Python 基础知识解开迷惑并查找答案--使用Python和Visual Studio Code破解代码和显示机密

介绍如何使用机密消息解码器

检查Visual Studio Code是否已准备好执行消息解码

在计算机上创建用于代码的文件玩意儿。文件夹命名为Sleuth。

鼠标放在Sleuth文件夹,右键点击“在终端中打开”。

输入命令行:

 打开Visual Studio Code

 创建文件,命名为“decrypt.py” 

 提示虚拟小镇“Contosoville”,输入代码,选择右上角的“运行”按钮,显示运行结果:

有关创建机密消息解码器的Python基础知识

注释:

带有符号(#)的行,Python会忽略该符号后的所有内容。

变量:

使用赋值等号(=)运算符。

函数:

一次使用Caesar密码解码一个字母

将字符转换为数字

ASCII字符代码是表示字母和数字的数值代码。

Python具有名为ord的函数,该函数可将字符转换为对应的ASCII字符代码。

计算解码的字符:简单方式

继续测试解码器

使用Caesar密码通过循环访问英语字母表来解码字母

Mod运算符

mod运算符将两个数相除并返回余数。

计算解码的字符:正确方式:

示例1:字母"a",移位2

示例2:字母"N",移位13

最终代码:

使用Caesar密码解码完整单词

将单词视为字母的集合

使用for循环实现列表迭代

调用lasso_letter()函数

将字母串在一起

注释代码

测试函数

查看完整文件

# Define a function to find the truth by shifting the letter by a specified amount
def lasso_letter( letter, shift_amount ):
    # Invoke the ord function to translate the letter to its ASCII code 
    # Save the code value to the variable called letter_code
    letter_code = ord(letter.lower())
    
    # The ASCII number representation of lowercase letter a
    a_ascii = ord('a')

    # The number of letters in the alphabet
    alphabet_size = 26

    # The formula to calculate the ASCII number for the decoded letter
    # Take into account looping around the alphabet
    true_letter_code = a_ascii + (((letter_code - a_ascii) + shift_amount) % alphabet_size)

    # Convert the ASCII number to the character or letter
    decoded_letter = chr(true_letter_code)

    # Send the decoded letter back
    return decoded_letter

# Define a function to find the truth in a secret message
# Shift the letters in a word by a specified amount to discover the hidden word
def lasso_word( word, shift_amount ):

    # This variable is updated each time another letter is decoded
    decoded_word = ""

    # This for loop iterates through each letter in the word parameter
    for letter in word:
        # The lasso_letter() function is invoked with each letter and the shift amount
        # The result (the decoded letter) is stored in a variable called decoded_letter
        decoded_letter = lasso_letter(letter, shift_amount)

        # The decoded_letter value is added to the end of the decoded_word value
        decoded_word = decoded_word + decoded_letter

    # The decoded_word is sent back to the line of code that invoked this function
    return decoded_word

# Try to decode the word "terra"
print( "Shifting terra by 13 gives: \n" + lasso_word( "terra", 13 ) )

使用Lasso解码器破译机密消息

添加prnint语句

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值