Chapter Review Questions#
Note
Source: Adapted from the C# edition (decisions/reviewdecisions.rst).
Questions 7–10 are original additions.
Two similar-looking operators.
What does
=do in Python?What does
==do?Give a one-line example of each.
Python’s Boolean operators.
Name all three.
How do they differ from the C# equivalents (
&&,||,!)?
What is printed?
x = 7 if x > 5: print("big") if x > 10: print("very big") else: print("not very big")
Short-circuit evaluation.
What does short-circuit evaluation mean?
Give an example where it prevents a runtime error.
Rewrite this nested
ifusing a single condition withand:if age >= 18: if has_id: print("Entry allowed.")
What is the bug in this code? Fix it.
score = 85 if score >= 90: grade = "A" if score >= 80: grade = "B" if score >= 70: grade = "C" print(grade)
Write a function
absolute_value(x)using anif/elsestatement that returns the absolute value ofxwithout usingabs().Write a function
sign(x)that returns1ifx > 0,-1ifx < 0, and0ifx == 0.Write a function
is_leap_year(year)that returnsTrueifyearis a leap year. A year is a leap year if it is divisible by 4, except centuries (divisible by 100) are not leap years, unless they are also divisible by 400.What does this expression evaluate to, and what type does it produce?
"pass" if 75 >= 60 else "fail"