首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么我们要移动"if“语句?

为什么我们要移动"if“语句?
EN

Stack Overflow用户
提问于 2021-12-30 07:34:27
回答 1查看 73关注 0票数 0

我不明白为什么要搬家

代码语言:javascript
复制
if cipher_direction == "decode":
      shift_amount *= -1

end_text下工作,但它不能在下面所示的位置工作?

完整的代码:

代码语言:javascript
复制
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']

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

#TODO-1: Combine the encrypt() and decrypt() functions into a single function
# called caesar().

def caesar(start_text, shift_amount, cipher_direction):
  end_text = ""
  if cipher_direction == "decode":
      shift_amount *= -1
  for letter in start_text:
    position = alphabet.index(letter)
    new_position = position + shift_amount
    end_text += alphabet[new_position]
  print(f"Here's the {direction}d result: {end_text}")


#TODO-2: Call the caesar() function, passing over the 'text', 'shift' and
# 'direction' values.
caesar(start_text=text, shift_amount=shift, cipher_direction=direction)
EN

回答 1

Stack Overflow用户

发布于 2021-12-30 08:04:00

因为变量赋值(*=)经常在循环中被覆盖。要在循环中使用它,需要分配一次。

例如:

代码语言:javascript
复制
def caesar(start_text, shift_amount, cipher_direction):
  end_text = ""
  #if cipher_direction == "decode":
  #  shift_amount *= -1
  for letter in start_text:
    if cipher_direction == "decode" and shift_amount > 0:
      shift_amount *= -1
    position = alphabet.index(letter)
    new_position = position + shift_amount
    end_text += alphabet[new_position]
    print(f"Here's the {direction}d result: {end_text}")

注意:程序在带有空格的单词中抛出一个错误。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70528660

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档