[英]How to add to "i" in a range in a For-Loop (Python)
這里相當初學者。 所以基本上,這是一個練習,將輸入的字母字符串轉換成它的 unicodes,然后再轉換回一個字符串(我知道這很愚蠢,但這是一個練習 eheh)。 所以我的代碼是:
OG_string = ""
while OG_string.isalpha() is False:
OG_string = input("Enter a message: ")
if not OG_string.isalpha():
print("Sorry, you can only enter letters")
secret_string = ""
for char in OG_string:
secret_string += str(ord(char))
print("The secret code is: ", secret_string)
OG_string = ""
for i in range(0, len(secret_string)-2, 2):
if int(secret_string[i]) == 1:
unicode = secret_string[i] + secret_string[i + 1] + secret_string[i + 2]
i += 1
else:
unicode = secret_string[i] + secret_string[i + 1]
OG_string += chr(int(unicode))
print("The original message is: ",OG_string)
僅使用大寫字母就可以輕松工作,因為所有數字都是 2 位數字(使用 len(secret_string)-1 而不是 2),但是現在有些數字是 3 位數字(大多數小寫的 unicodes),我無法讓它工作,並且我發出的原始消息很奇怪,因為它似乎適用於前 3 個字母,而不適用於其余字母(如果我輸入“你好”)。 下面是一個例子:
Enter a message: Hello
The secret code is: 72101108108111
The original message is: HelQ
如果我輸入“香蕉”,我會得到(原始消息是:Ban Gm)。 我知道 Q 的 unicode 是 81,稍后會出現,但為什么會這樣? 一個解決方案是在轉換為 ord 時減去 23,然后在第二行到最后一行執行 chr 時將其添加回來(因為 z 是 122),但我想通過另一條路線嘗試。
在此先感謝您的任何幫助 ;)
PS 對於我原來的 Do-while 循環,是否有任何理由更喜歡“While True”然后在其中某處“break”而不是做我所做的? 似乎老師會做“雖然是真的”,但如果有區別,則是 IDK。 我也做了“while X...False”和“if not X”來提醒自己兩者都有效,但它們總是可以互換嗎?
不要在循環內使用 for 循環的控制變量。
也就是說,重寫:
for i in range(10):
if i % 3 == 0:
i += 1
print(i)
...到:
i = 0
while i < 10:
if i % 3 == 0:
i += 1
print(i)
i += 1
您的 for 循環遍歷一組固定的對象,因此您的 i+=1 行沒有效果。 要改變這一點,我建議使用 while 循環:
OG_string = ""
while OG_string.isalpha() is False:
OG_string = input("Enter a message: ")
if not OG_string.isalpha():
print("Sorry, you can only enter letters")
secret_string = ""
for char in OG_string:
secret_string += str(ord(char))
print("The secret code is: ", secret_string)
OG_string = ""
i=0
while i<len(secret_string)-2:
if int(secret_string[i]) == 1:
unicode = secret_string[i:i+3]
i += 3
else:
unicode = secret_string[i:i+2]
i += 2
print(unicode)
OG_string += chr(int(unicode))
print("The original message is: ",OG_string)
OG = ""
while OG.isalpha() is False:
OG = input("Enter a message: ")
if not OG.isalpha():
print("Sorry, you can only enter letters")
asc = []
for char in OG:
asc.append(str(ord(char)))
print("The secret code is: ", asc)
print( ''.join(asc ) ) # if you want a string
OG2=""
for i in range(len(asc)):
OG2 += chr(int(asc[i]))
print("The original message is: ",OG2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.