题目
下面if语句统计满足“性别(gender)为男、职称(rank)为副教授、年龄(age)小于40岁”条件的人数,正确的语句为( ).A. if(gender=="男" or ageB. if(gender=="男" and ageC. if(gender=="男" and ageD. if(gender=="男" or age
下面if语句统计满足“性别(gender)为男、职称(rank)为副教授、年龄(age)小于40岁”条件的人数,正确的语句为( ).
A. if(gender=="男" or age<40 and rank=="副教授"): n+=1
B. if(gender=="男" and age<40 and rank=="副教授"): n+=1
C. if(gender=="男" and age<40 or rank=="副教授"): n+=1
D. if(gender=="男" or age<40 or rank=="副教授"): n+=1
题目解答
答案
B. if(gender=="男" and age<40 and rank=="副教授"): n+=1
解析
本题考查逻辑运算符的优先级及条件组合的正确写法。解题核心在于理解题目要求的条件是三个条件同时成立(性别为男、职称是副教授、年龄小于40岁),因此需要使用逻辑与(and)连接所有条件。需注意运算符优先级:and
的优先级高于or
,若混合使用需通过括号明确逻辑关系。
选项分析
选项A
if(gender=="男" or age<40 and rank=="副教授")
- 逻辑解析:等价于
gender=="男"
或(age<40 and rank=="副教授")
- 错误原因:满足性别为男或同时满足年龄、职称条件即可,未要求三个条件同时成立。
选项B
if(gender=="男" and age<40 and rank=="副教授")
- 逻辑解析:三个条件通过
and
连接,要求同时满足。 - 正确性:符合题目要求,所有条件必须同时成立。
选项C
if(gender=="男" and age<40 or rank=="副教授")
- 逻辑解析:等价于
(gender=="男" and age<40)
或rank=="副教授"
- 错误原因:满足性别与年龄条件或职称条件即可,未要求三个条件同时成立。
选项D
if(gender=="男" or age<40 or rank=="副教授")
- 逻辑解析:三个条件通过
or
连接,满足任意一个即可。 - 错误原因:未要求三个条件同时成立。