如何添加一行代码反转总统资格判定程序的输出结果?
解决方法
要实现输出反转,核心是用Python的not布尔运算符——它能把True变成False,False变成True,正好匹配你的需求。这里有两种简单的实现方式:
方式1:先存结果再反转(更清晰,适合新手理解)
把原来的资格判断结果存到变量里,再对变量取反输出:
age = int(input('How old are you? ')) born_in_us = (input('Were you born in the US? ')) residence = int(input('How long have you lived in the United States? ')) # 先判断是否符合总统资格,存到变量中 is_eligible = age >= 35 and residence >= 14 and born_in_us == 'Yes' # 反转结果输出 print(not is_eligible)
方式2:直接在判断表达式前加not
如果不想额外定义变量,也可以直接在原判断表达式前加not:
age = int(input('How old are you? ')) born_in_us = (input('Were you born in the US? ')) residence = int(input('How long have you lived in the United States? ')) # 直接对原判断结果取反输出 print(not (age >= 35 and residence >= 14 and born_in_us == 'Yes'))
两种方法都能达成目标:符合总统资格时输出False,不符合时输出True。
内容的提问来源于stack exchange,提问作者vividri
相关产品推荐
相关产品推荐

