首先,您应该将输入/输出与处理分离,因为您的代码将更容易测试:
def cipher(code, distance):
plainText = ""
for ch in code:
ordvalue = ord(ch)
ciphervalue = ordvalue - distance
if ciphervalue < ord('a'):
ciphervalue = ord('z') - (distance - (ord('a')-ordvalue - 1))
plainText += chr(ciphervalue)
return plainText
code = input("enter coded text: ")
distance = int(input("enter value: "))
print(cipher(code, distance))
现在,你有:
>>> cipher("Lipps${svph%", 4)
'\x8aello²world±'
我猜你期待像“Hello world!”这样的东西。如果您删除这两行,就会得到这样的结果:
if ciphervalue < ord('a'):
ciphervalue = ord('z') - (distance - (ord('a')-ordvalue - 1))
看:
def cipher2(code, distance):
plainText = ""
for ch in code:
ordvalue = ord(ch)
ciphervalue = ordvalue - distance
plainText += chr(ciphervalue)
return plainText
>>> cipher2("Lipps${svph%", 4)
'Hello world!'
>>> cipher2("Jhss'tl'Pzothls5", 7)
'Call me Ishmael.'
>>> cipher2("Zu&hk2&ux&tuz&zu&hk", 6) # was 2, but I guess it's 6
'To be, or not to be'
>>> cipher2("khoor#zruog$", 3)
'hello world!'
这是问题的有趣部分。但我认为您的直觉是正确的:当生成的 ordvalue 值不在预期范围内(即负数或大)时会发生什么?
>>> cipher2("hello", 103)
Traceback (most recent call last):
...
ValueError: chr() arg not in range(0x110000)
函数ord 产生一个介于 0 和 1114111 之间的 unicode 代码点,但我认为对于练习,您可以将范围限制为 0 - 127(ASCII 字符):
def cipher3(code, distance):
assert abs(distance) < 128
plainText = ""
for ch in code:
ordvalue = ord(ch)
ciphervalue = ordvalue - distance
if ciphervalue < 0:
ciphervalue += 128
elif ciphervalue >= 128: # don't forget distance can be negative
ciphervalue -= 128
plainText += chr(ciphervalue)
return plainText
>>> cipher3("hello", 103)
'\\x01~\\x05\\x05\\x08'
>>> cipher3('\x01~\x05\x05\x08', -103)
'hello'
请注意:
if ciphervalue < 0:
ciphervalue += 128
elif ciphervalue >= 128: # don't forget distance can be negative
ciphervalue -= 128
相当于:
ciphervalue = ciphervalue % 128
如果你只想有可打印的字符,你可以使用string 模块:
import string
# string.printable is '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
def cipher4(code, distance):
assert abs(distance) < len(string.printable)
plainText = ""
for ch in code:
ordvalue = string.printable.index(ch) # this is clearly suboptimal
ciphervalue = (ordvalue - distance) % len(string.printable)
plainText += string.printable[ciphervalue]
return plainText
>>> cipher4("hello", 80)
'ByFFI'
>>> cipher4('ByFFI', -80)
'hello'