以下是Python的code,這次沒有註解,因為寫的時候有點想睡,想寫快點,而且函數名稱都很明顯了,有看不懂再問吧:
def checkint(c):
while True:
try:
c = int(c)
return c
except:
print ("Invaild value!")
c = input("Enter shift value again:")
def checkempty(s):
while s=="":
print ("No sentence.")
s = input("Enter sentence to encrypt again:")
return s
def shiftletter(word, c):
new_word = []
for letter in word:
temp=ord(letter)
if temp in range(65, 91):
temp+=c
temp = (temp-65)%26+65
elif temp in range(97, 123):
temp+=c
temp = (temp-97)%26+97
new_word.append(chr(temp))
return "".join(new_word)
def encode(Input, c):
word_list = Input.split()
new_word_list = []
for word in word_list:
new_word_list.append(shiftletter(word, c))
return " ".join(new_word_list)
#My "Restart" option
def exit(ans):
while True:
ans = str(ans).lower()
if ans == "y":
print ("See You!")
input ("Press enter to continue")
raise SystemExit()
elif ans == "n":
return "n"
else:
print ()
print ("Invalid Input")
ans = input("Exit? (y/n)")
#End of "Restart"
def main():
Input = checkempty(input("Enter sentence to encrypt:"))
c = checkint(input("Enter shift value:"))
#for test
#Input = "Mayday! Mayday!"
#c = input("Enter shift value:")
#end for test
print ("The encoded phrase is:", encode(Input, c))
print ("Welcome to Caesar cipher!")
print ()
re = "n"
while re=="n":
main()
print ()
re = exit(input("Exit? (y/n)"))
print ()
print ()
效果:
首先顯示歡迎字句,然後問要加密的句子,如果沒有輸入句子就會要你重新輸入。然後到輸入順移次數,如果輸入非整數就會顯示輸入無效,直至輸入為整數。之後就會輸出加密後的句子,數字和符號不會改變。最後問你是否離開,答y就會結束,答n的話就會再來一次。

沒有留言 :
張貼留言