加密和解密项目未使用循环结束



我一直在做一个有趣的小项目,对一些消息进行加密,然后可能对它们进行解密。唯一的问题是,当我调用类的实例时,它会到达,但之后它再也不会回来并继续运行。有什么技巧可以解决这个问题吗,谢谢!

import datetime
beta_value = {"A":5, "B":9, "C":11, "D":12, "E":13, "F":14, "G":8, "H":6, "I":7, "J":15, "K":16, "L":4, "M":17, "N":18, "O":19, "P":20, "Q":10, "R":21, "S":22, "T":23, "U":24, "V":3, "W":25, "X":26, "Y":27, "Z":28, "": 0, ".": 1, "!": 2}
#Find the day
d = datetime.datetime.now()
day = d.strftime("%d")
#The beta value is the value for each letter in the alphabet that is the number of nodes it takes to construct the capital counter part of that letter, and +n if needed
#Create the encryption and decryption class
class Beta():
def __init__(self, sen):
self.liste = []
self.listd = []
#Leaf through the letter for encryption or decryption
for let in sen:
self.liste.append(self.encrypt(let))
self.listd.append(self.decrypt(let))
# resulte = 
# resultd = 
#Create encryption
def encrypt(self, let):
allowed = True
beta_uf = int((int(beta_value[let.capitalize()]) + int(day)) % 28)
#Check if the beta value exists in the beta_value list
while allowed:
for key, value in beta_value.items():
if int(beta_uf) == value:
beta_f = key
allowed = False
if allowed:
beta_uf += 1
return beta_f
#Create decryption
def decrypt(self, let):
pass
#Input words
words = input("What is your text? ")
#Create instance of the class
B = Beta(words)
#Encrypt or decrypt?
e_or_d = input("Encrypt or Decrypt? ")
if e_or_d == "encrypt" or "Encrypt":
print(B.liste)
else:
print(B.listd)

另外,请不要批评我这有多糟糕…

后续:嗨,下面的评论帮助解决了我的主要问题(我也从上面更新了我的代码到新的东西(,但现在我想尝试包括空格,但似乎有一个问题:

Traceback (most recent call last):
File "main.py", line 49, in <module>
B = Beta(words)
File "main.py", line 19, in __init__
self.liste.append(self.encrypt(let))
File "main.py", line 28, in encrypt
beta_uf = int((int(beta_value[let.capitalize()]) + int(day)) % 28)
KeyError: ' '

哈哈,女,我修好了……:p

您的代码中有几件事可能是他们自己的问题,但这是关于为什么您的代码"被卡住";并且不返回任何值。

原因是while循环没有达到退出条件,而是陷入了无限循环。

你的while循环基本上是这样做的:

while True:
for i in range(10):
break

在for循环内部发出的CCD_;"爆发";从for循环,不要触摸while循环的状态。

有多种方法可以解决这个问题。解决这个问题的一种方法是进一步进行流控制,并使用for循环(经常被遗忘(else语句。

只有在整个for循环执行到完成时,才会执行for循环后面的else语句。

让我们用这段代码看看它的作用:

>>> for i in range(3):
...     print(i)
... else:
...     print("The for-loop was executed to its end.")
... 
0
1
2
The for-loop was executed to its end.

如果我们将这种行为与continue语句一起使用,那么我们可以进行while循环";错过";它自己的CCD_ 3语句。

这里有一个(不那么简单(的例子:

import random
while True:
for i in range(3):
rint = random.randint(0,10)
print(f'range {i=} {rint=}')
if i == rint:
print("Breaking the for-loop.")
break
else: # Only runs when the whole for-loop was executed.
print("Continuing to the next for-loop!")
continue
print("Breaking the while-loop.")
break

一次运行的输出:

range i=0 rint=6
range i=1 rint=0
range i=2 rint=0
Continuing to the next for-loop!
range i=0 rint=0
Breaking the for-loop.
Breaking the while-loop.

最新更新