-1

Why are Options 1 and 4 correct and 2 and 3 not?

Variables grade1 and grade2 represent grades in two courses. Variable num_passed currently refers to 0. Select the code fragment(s) that make num_passed refer to the number of courses passed (with a 50 or higher).

Option 1
if grade1 >= 50:
 num_passed = num_passed + 1
if grade2 >= 50:
 num_passed = num_passed + 1

Option 2
if grade1 >= 50:
 num_passed = num_passed + 1
elif grade2 >= 50:
 num_passed = num_passed + 1

Option 3 
if grade1 >= 50 and grade2 >= 50:
 num_passed = 2
if grade1 >= 50:
 num_passed = 1
if grade2 >= 50:
num_passed = 1

Option 4 
if grade1 >= 50 and grade2 >= 50:
 num_passed = 2
elif grade1 >= 50:
 num_passed = 1
elif grade2 >= 50:
 num_passed = 1
4

2 回答 2

1

if and elif are mutually-exclusive clauses: either one fires, or the other one does, or else neither does - never both. So in (1), both fire, and that's fine because you're adding to num_passed, not setting it to a specific value. (2) doesn't do what you want because, by definition, if one clause fires then the other one doesn't. (3) doesn't do what you want because each clause gets evaluated and the last one that fires wins. For example if both grades are passing, then you set num_passed to 2, and then you set it to 1 and then you set it to 1 again. (4) works because it avoids the trap of three - exactly one (or none) of the clauses will fire.

于 2013-09-07T20:21:59.687 回答
0

This should be elementary logic. grade1 and grade2 are independent variables, and either, both or neither can be over 50.

于 2013-09-07T20:17:32.303 回答