You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何添加一行代码反转总统资格判定程序的输出结果?

解决方法

要实现输出反转,核心是用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 20:25:22