在Python

时间:2017-12-10 16:36:17

标签: python

我无法在下面更正我的编码,并且由于某种原因代码没有运行。请帮我纠正,如果可能的话,请建议更好的编码实践,并帮助缩短编码时间:

message = input ('Enter your message')

key = int (input('How many Characters should we shift(between 1 - 26)- '))

secret-message = ""
for char in message:

    if char.isalpha():
        #Get the character code and add the shift amount
        char_code = ord(char)
        chat_code += key
        #if upper case then compare to uppercase unicode
        if char.isupper():
            #if upper than Z substract 26
            if char_code > ord('Z'):
                char_code -= 26
            #if smaller than A add 26
            if char_code < ord('A'):
                char_cod += 26
        #Do the same for lower character
        else:
            if char_code > ord('z'):
                char_code -= 26
            if char_code < ord('a'):
                char_cod += 26
        #Convert From Code to letter and add to message
    secret-message = secret-message + chr(char_code)
    else:
        secret-message = secret-message + char
print (" Encripted :" , secret-message)

1 个答案:

答案 0 :(得分:0)

除了与代码中的变量不一致之外,您在-中使用secret-message运算符,因为您获得了SyntaxError: can't assign to operator。经过这些更正后,您的代码正在运行:

message = input('Enter your message: ')

key = int(input('How many Characters should we shift(between 1 - 26)- '))

secret_message = ""

for char in message:
    if char.isalpha():
        #Get the character code and add the shift amount
        char_code = ord(char)
        char_code += key
        #if upper case then compare to uppercase unicode
        if char.isupper():            
            #if upper than Z substract 26
            if char_code > ord('Z'):
                char_code -= 26
            #if smaller than A add 26
            if char_code < ord('A'):
                char_code += 26
        #Do the same for lower character
        else:
            if char_code > ord('z'):
                char_code -= 26
            if char_code < ord('a'):
                char_code += 26
        #Convert From Code to letter and add to message                
        secret_message = secret_message + chr(char_code)
    else:
        secret_message = secret_message + char

print (" Encripted :" , secret_message)

运行它:

Enter your message: secret
How many Characters should we shift(between 1 - 26)- 5
 Encripted : xjhwjy
>>> 

现在您的代码正常运行,并且由于您对更好的编码练习感兴趣,您可能希望在Code Review Stack Exchange发布相同的代码,以便进行同行程序员代码审核。

希望有所帮助。