为什么这些变量不能正确地输出它们的值呢?

2024-03-28 12:20:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前使用的是python3.5,字典中的变量有问题。我把数字1-29作为键,字母作为它们的对,由于某种原因,没有一个两位数的数字注册为一个数字。例如,11表示1和1(F和F),而不是11(I),或者13表示1,3表示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)

Tags: to代码in字典字母数字eodict
1条回答
网友
1楼 · 发布于 2024-03-28 12:20:48

您的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]

因为dict有键'11',而您的textIn等于'11'。你知道吗

代码中还有另一个主要问题;textOut变量在每个循环中都会被覆盖,因此您会丢失所做的一切。您想在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)

相关问题 更多 >