我有一個問題,當我要求我的程序退出時,打印就像我問它,但顯示我的選項菜單以及不斷。雖然循環失敗 - 凱撒密碼
所以我得到這樣的:
>>>
(S)huffle a message.
(U)nshuffle a message.
(Q)uit program.
Choose a option to begin: q
Goodbye!
(S)huffle a message.
(U)nshuffle a message.
(Q)uit program.
Choose a option to continue:
,我想如果我選擇「Q」它來顯示這一點:
>>>
(S)huffle a message.
(U)nshuffle a message.
(Q)uit program.
Choose a option to begin: q
Goodbye!
這裏是我的完整代碼,請解釋一下爲什麼我的菜單是重新打印,我是否讓我的while循環錯誤,或者是在我的代碼中不合適的地方?
def hw8():
print('(S)huffle a message.')
print('(U)nshuffle a message.')
print('(Q)uit program.')
x = input('Choose a option to begin: ')
if x == 'Q' or x == 'q':
print('Goodbye!')
while x != 'q' or 'Q' :
if x == 'S' or x == 's':
y = input('Enter a message to shuffle: ')
q1 = ''
for i in y:
if ord(i) in range(65,90) or ord(i) in range(97,122):
q = chr(ord(i) + 1)
q1 = q1 + q
elif ord(i) == 90:
q = chr(ord(i) + 7)
q1 = q1 + q
elif ord(i) == 122:
q = 'A'
q1 = q1 + q
else:
q = i
q1 = q1 + q
print(q1)
if x == 'U' or x == 'u':
f = input('Enter a message to unshuffle: ')
t2 = ''
for i in f:
if ord(i) in range (66,91) or ord(i) in range(98,123):
t = chr(ord(i) - 1)
t2 = t2 + t
elif ord(i) == 65:
t = 'z'
t2 = t2 + t
elif ord(i) == 97:
t = 'Z'
t2 = t2 + t
else:
t = i
t2 = t2 + t
print(t2)
print('(S)huffle a message.')
print('(U)nshuffle a message.')
print('(Q)uit program.')
x = input('Choose a option to continue: ')
hw8()
我希望程序洗牌的消息,或unshuffling消息後,以及在開始顯示菜單,而不是在用戶已經要求通過選擇「Q」退出程序。
編輯的代碼:
def hw8():
print('(S)huffle a message.')
print('(U)nshuffle a message.')
print('(Q)uit program.')
x = input('Choose a option to begin: ')
while x != 'q' or x != 'Q' :
if x == 'S' or x == 's':
y = input('Enter a message to shuffle: ')
q1 = ''
for i in y:
if ord(i) in range(65,90) or ord(i) in range(97,122):
q = chr(ord(i) + 1)
q1 = q1 + q
elif ord(i) == 90:
q = chr(ord(i) + 7)
q1 = q1 + q
elif ord(i) == 122:
q = 'A'
q1 = q1 + q
else:
q = i
q1 = q1 + q
print(q1)
if x == 'U' or x == 'u':
f = input('Enter a message to unshuffle: ')
t2 = ''
for i in f:
if ord(i) in range (66,91) or ord(i) in range(98,123):
t = chr(ord(i) - 1)
t2 = t2 + t
elif ord(i) == 65:
t = 'z'
t2 = t2 + t
elif ord(i) == 97:
t = 'Z'
t2 = t2 + t
else:
t = i
t2 = t2 + t
print(t2)
print('(S)huffle a message.')
print('(U)nshuffle a message.')
print('(Q)uit program.')
x = input('Choose a option to continue: ')
if x == 'Q' or x == 'q':
print('Goodbye!')
hw8()
新輸出:
>>> ================================ RESTART ================================
>>>
(S)huffle a message.
(U)nshuffle a message.
(Q)uit program.
Choose a option to begin: s
Enter a message to shuffle: hello
ifmmp
(S)huffle a message.
(U)nshuffle a message.
(Q)uit program.
Choose a option to continue: q
Goodbye!
(S)huffle a message.
(U)nshuffle a message.
(Q)uit program.
Choose a option to continue:
除了你可以考慮使用正確的答案了'而x.lower()=「Q」!......還有:打印(「再見」 )'。這節省了一個if語句,並在我看來更清楚地表達了意圖。 – Pyranja