2017-06-28 33 views
-1

我目前在Python 3.5中工作,並且遇到了我的字典中的變量問題。我有數字1-29作爲鍵,以字母作爲它們的對,並且由於某種原因,沒有一個雙數字數字註冊爲一個數字。例如,11會以1和1(F和F)出現,而不是11(I)或13以及3(F和TH)而不是13(EO)。有沒有辦法解決這個問題,以便我可以得到兩位數字的值?爲什麼這些變量不能正確輸出它們的值?

我的代碼是在這裏:

Dict = {'1':'F ', '2':'U ', '3':'TH ', '4':'O ', '5':'R ', '6':'CoK ', '7':'G ', '8':'W ', '9':'H ', 
     '10':'N ', '11':'I ', '12':'J ', '13':'EO ', '14':'P ', '15':'X ', '16':'SoZ ', '17':'T ', 
     '18':'B ', '19':'E ', '20':'M ', '21':'L ', '22':'NGING ', 
     '23':'OE ' , '24':'D ', '25':'A ', '26':'AE ', '27':'Y ', '28':'IAoIO ', '29':'EA '} 

textIn = ' ' 

#I'm also not sure why this doesn't work to quit out 
while textIn != 'Q': 
    textIn = input('Type in a sentence ("Q" to quit)\n>') 
    textOut = '' 
    for i in textIn: 
     if i in Dict: 
      textOut += Dict[i] 
     else: 
      print("Not here") 
    print(textOut) 
+0

for循環遍歷輸入字符串中的每個單個字符_。 – ForceBru

+0

沒有辦法檢測到你的意思是'11',而不是'1'和'1'。你可能想要改變你的「字母表」。而且你正在迭代整個字符串中的單個字符。 – bakatrouble

+0

你可以舉一個你期望從用戶那裏得到的輸入形式的例子嗎? –

回答

1

for i in textIn:將循環在你輸入的單個字符。所以,如果你寫11,它實際上是一個字符串'11',並且for i in '11'會在'1'的分別:

>>> text = input() 
13 
>>> text 
'13' # See, it's a string with the single-quote marks around it! 
>>> for i in text: 
...  print(i) 
... 
1 
3 
>>> # As you see, it printed them separately. 

你不需要for循環可言,你可以使用:

if textIn in Dict: 
    textOut += Dict[textIn] 

由於您的字典有密鑰'11',而您的textIn等於'11'

您的代碼中還存在其他主要問題;變量會被覆蓋,每循環,所以你失去了你所做的一切。您想在while循環之外創建它:

textOut = '' 
while textIn != 'Q': 
    textIn = input('Type in a sentence ("Q" to quit)\n>') 
    if textIn in Dict: 
     textOut += Dict[textIn] 
    else: 
     print("Not here") 

print(textOut) 
+0

謝謝,這比我在做的事更有意義。雖然我還有一個問題。是應該看起來像這樣的代碼呢? textIn = '' 的TextOut = '' 而textIn = 'Q': textIn =輸入( '在一個句子( 「Q」 退出型)\ n>') 如果textIn在字典: 的TextOut + =快譯通[textIn] 其他: 打印(「不在這裏」) 打印(的TextOut) 我問,因爲它不工作讓我爲我輸入一個值。 – KnittedCupcake

+0

你是什麼意思,它不工作? @KnittedCupcake我的代碼似乎對我很好。 –

相關問題