Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

python - Why is this basic if-else expression failing?

This is my first post on the site. I am in my third week of coding class and have completed everything but this problem. We are using ZyBooks. I have completed everything but this participation exercise. It isn't graded; however, it is driving me nuts. We are asked to write an expression that will print "in high school" if the value of user_grade is between 9 and 12 (inclusive).

Sample output with input: 10 in high school

This is what I have so far: I apologize if I am posting this incorrectly.

user_grade = int(input())
if user_grade >= 9 <= 12:
    print('in high school')
else:
    print('not in high school')

The code passes all tests until it runs input: 13. Then I receive this error:

Output differs. See highlights below.

Special character legend Your output: in high school

Expected output: not in high school

question from:https://stackoverflow.com/questions/65866137/why-is-this-basic-if-else-expression-failing

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think your order of operations in the if is slightly wrong. Do you mean the following:

if  9 <= user_grade <= 12:

Because right now you are checking:

  • is 9 smaller or equal to user_grade AND
  • is 9 smaller or equal to 12

If you enter 13 then the first check will be True. But as the second check is only comparing 9 and 12 it is always true. And therefore you are never testing if user_input is smaller or equal to 12.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...