【问题标题】:Trying to make an encryption code but gets many errors尝试制作加密代码但出现许多错误
【发布时间】:2020-02-06 03:45:02
【问题描述】:
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"," ","."]
print(alphabet[0])
user_input = "this is a test."
user_sentance = list(user_input)

print(user_sentance)

#user_sentance = user_input.split()
#print(user_sentance)
counter = 0

#def remove_space():
 #   return string.replace(" ", "")

#def remove_period():
#    user_sentance.replace(".", "")

counter_1 = 0

def counter_2():
    counter_2 = 0   


def counter_1():
    counter_1 = 0   

def main():
    for i in user_sentance:
        counter_1 = 0
        counter_2 = 0
        for x in alphabet:

            if user_sentance[counter_1] == alphabet[counter_2]:
                print(counter_2)
                main()
                counter_2 = 0
            else:
                main()
                counter_2 += 1
        counter_1 += 1

        #if "." in user.sentance[counter]:
         #   user_sentance[counter].replace(".","")
          #  print(user_sentance)
           # main()
        #else:
        #    break


main()

这是它正在打印的内容:

a

['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't', '.']

然后错误从这里开始:

Traceback (most recent call last):
  File "C:/Users/Shah family/Desktop/Coding/python/encrypted code.py", line 52, in <module>
    main()

  File "C:/Users/Shah family/Desktop/Coding/python/encrypted code.py", line 40, in main
    main()

  File "C:/Users/Shah family/Desktop/Coding/python/encrypted code.py", line 40, in main
    main()

  File "C:/Users/Shah family/Desktop/Coding/python/encrypted code.py", line 40, in main
    main()

 [Previous line repeated 989 more times]

 File "C:/Users/Shah family/Desktop/Coding/python/encrypted code.py", line 35, in main
    if user_sentance[counter_1] == alphabet[counter_2]:

RecursionError: maximum recursion depth exceeded in comparison

我该怎么办???

【问题讨论】:

  • 您应该停止从main() 拨打main()
  • 您使用的递归函数没有停止/中断条件。
  • 你应该:删除所有注释掉的代码;删除无意义的counter_1counter_2 函数;在没有合适的停止条件的情况下,不要从 main() 调用 main() 此递归 - 或者可能更好,将递归放在定义明确的递归函数中并从 main() 调用一次。
  • 程序应该做什么?如果我们不知道您想要的结果,包括您是否打算使用递归,我们无法推荐解决方案。

标签: python python-3.x recursion encryption counter


【解决方案1】:

您没有结束循环的条件。第 38 行的main() 不断被调用,并且程序停止,因为它处于无限循环中。

你应该做什么,修复你的 if 语句,让它有一个条件来结束或中断循环,比如 bool 值,或者返回,或者查看这篇文章的评论。

同时递归调用主函数也不是一个好主意,这就是制作其他函数的目的。

【讨论】:

  • 添加 waitexit 调用只会加剧已经很糟糕的解决方案 - 递归函数可以在达到停止条件时简单地返回适当的值(或 None,如果合适的话)。
  • 我同意这种说法。我只是想指出,当我应该说循环时,应该有一个结束程序的条件。你是对的,即使它什么都没有,该函数也应该返回一些东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多