Python GetCh vs For循环

2024-09-30 22:26:51 发布

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

我需要帮助让我的条件语句使用For循环查看数组值。你知道吗

我的印象是,这可能是因为我没有像在其他两个if语句中那样使用b'X',但我就是想不出正确的语法来实现这一点,而且我甚至不知道b在那里做什么。你知道吗

R和X击键确实正确地执行了它们的代码,但是作为FOR循环的一部分被检查的p、N、D和Q却不正确。你知道吗

Token = [['P',0,.01,"Penny"],['N',0,.05,"Nickel"],['D',0,.10,"Dime"],['Q',0,.25,"Quarter"]]

def GetKey(CoinIn): # Recieve a coin, update all total counts and values
    if CoinIn == b'R':     # Reset All Values and counts to 0
        for i in Token:
            i[1] = 0
    elif CoinIn == b'X':   # Exit Request
        return('X')
    else:                 # HERE IS WHERE THE CODE BREAKS
        for i in Token:
            if CoinIn == i[0]:
                i[1] += 1

对于更多上下文,the entire project是GitHub上的开源。你知道吗


Tags: and代码intokenforif语法数组
1条回答
网友
1楼 · 发布于 2024-09-30 22:26:51

我认为你的代码应该是正确的。但这取决于GetKey()的输入。你知道吗

我在底部添加了以下几行:

GetKey('P')
GetKey('P')
print(Token)

GetKey('N')
GetKey('D')
print(Token)

GetKey('Q')
print(Token)

我得到了这个结果:

[['P', 2, 0.01, 'Penny'], ['N', 0, 0.05, 'Nickel'], ['D', 0, 0.1, 'Dime'], ['Q', 0, 0.25, 'Quarter']]
[['P', 2, 0.01, 'Penny'], ['N', 1, 0.05, 'Nickel'], ['D', 1, 0.1, 'Dime'], ['Q', 0, 0.25, 'Quarter']]
[['P', 2, 0.01, 'Penny'], ['N', 1, 0.05, 'Nickel'], ['D', 1, 0.1, 'Dime'], ['Q', 1, 0.25, 'Quarter']]

另一方面,如果将字节而不是字符串传递给GetKey(),如下所示:

GetKey(b'P')
GetKey(b'P')
print(Token)

GetKey(b'N')
GetKey(b'D')
print(Token)

GetKey(b'Q')
print(Token)

你只会看到这一行重复:

[['P', 0, 0.01, 'Penny'], ['N', 0, 0.05, 'Nickel'], ['D', 0, 0.1, 'Dime'], ['Q', 0, 0.25, 'Quarter']]

这是因为Token中的硬币代码是字符串'P' 'N' 'D' 'Q'。如果将它们与b'P' b'N' b'D' b'Q'进行相等比较,结果将是False,因此需要将Token更改为如下所示:

Token = [[b'P',0,.01,"Penny"],[b'N',0,.05,"Nickel"],[b'D',0,.10,"Dime"],[b'Q',0,.25,"Quarter"]]

我想有一个很好的理由,像硬件一样,使用字节而不是字符串。你知道吗

相关问题 更多 >