12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 5Conditionals and recursion5.1 Modulus operatorThemodulusoperatorworksonintegersandyieldstheremainderwhenthefirstoperandisdividedby the second. In <strong>Python</strong>, the modulus operator is a percent sign (%). The syntax is the same as forother operators:>>> quotient = 7 / 3>>> print quotient2>>> remainder = 7 % 3>>> print remainder1So 7divided by 3is2with1leftover.The modulus operator turns out to be surprisingly useful. For example, you can check whether onenumber is divisibleby another—ifx % yiszero, thenxisdivisiblebyy.Also, you can extract the right-most digit or digits from a number. For example, x % 10 yields theright-mostdigit ofx(inbase 10). Similarlyx % 100yields thelast twodigits.5.2 BooleanexpressionsA boolean expression is an expression that is either true or false. The following examples usethe operator ==, which compares two operands and produces True if they are equal and Falseotherwise:>>> 5 == 5True>>> 5 == 6FalseTrueandFalsearespecial values that belong tothetypebool;they are not strings:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!