在Python中是否有充分的理由将布尔标志的初始值设置为'False'?

问题描述 投票:0回答:1

我已经注意到,布尔标志的初始值倾向于设置为'False',在这里您可以执行相同的代码将值设置为'True'。例如,让我们在这里看这段代码-

#Coin change exercise program
#The purpose of this program is to enter a number of coin values
#which add to to a displayed target value 
import random

print('Hit return after the last entered coin value.')
print('You can only add 1,5,10,25')

terminate = False #initial value
empty_str = ''

while not terminate: #you can withdraw the not part if the value is True
    amount = random.randint(1,99)
    print('Enter coins that add up to', amount, 'cents.\n')
    game_over = False #initial value
    total = 0

    while not game_over: #you can withdraw the not part if the value is True
        valid_entry = False #initial value

        while not valid_entry: #you can withdraw the not part if the value is True
            if total == 0:
                entry = input('Enter first coin: ')
            else:
                entry = input('Enter next coin: ')

            if entry in (empty_str,'1','5','10','25'):
                valid_entry = True
            else:
                print('Invalid entry')

        if entry == empty_str:
            if total == amount:
                print('Correct!')
            else:
                print('Sorry - you only entered', total, 'cents.')

            game_over = True
        else:
            total = total + int(entry)
            if total> amount:
                print('Sorry - total amount exceeds', amount, 'cents.')
                game_over = True

        if game_over: #you can put not if the value is True
            entry = input('\nTry again (y/n)?: ')

            if entry == 'n':
                terminate = True

print('Thanks for playing ... goodbye') 

对于此代码,您可以轻松地将值设置为'True'来获得相同的输出。以“ False”值编写代码只会使初学者更难理解算法。我只想知道有什么特殊原因吗?

python
1个回答
0
投票

请记住,Python是动态类型的,并使用“鸭子类型”,因此名称是否绑定到TrueFalse的布尔值实际上仅在使用它的上下文中重要。其他对象也可以求值为TrueFalse:空字符串和空列表/ dict /等都是Falsey。没有规则说在任何特定情况下都应将这样的变量设置为一个事物或另一事物。这取决于它的使用方式(如果以后会一直设置为True,则毫无意义地设置为False)。

热门问题
推荐问题
最新问题