6 > 5True
Reading: Think Python Chapters 5 and 7
Is 6 greater than 5? Obviously yes.
In Python, comparisons between values are accomplished with expressions using comparison operators.
These expressions return special values True and False. Be careful: these are not the same as strings "True" and "False". You can access them directly by typing True or False without any quotation marks.
True and False are Boolean variables, or “Bools” for short. There are only two Bools: True and False. Ambiguity can exist in society and philosophy, but it is not permitted in Python.
There are six comparison operators:
> (greater than)>= (greater than or equal to)< (less than)<= (less than or equal to)== (equal to)!= (not equal to)Take care with the difference between = and ==.
= (single equals) is assignment:
= is evaluated== (double equals) is equality comparison:
== are comparedTrueFalseComparison between numbers is straightforward:
Floats are equal to ints when they are numerically exactly equal.
Equality can be used between almost any two values:
The above expression is False because the string "3" is not numerically equal to the integer 3!
Strings are equal when they are the same.
String comparison checks for alphabetical order if all letters are lowercase or all letters are uppercase. c comes before e in the alphabet, so the position of c is “less than” the position of e.
Equality can be used to check if something is None.
Remember, True and False are not strings:
Some comparisons make no sense, such as between strings and numbers. If you try these, you’ll get an error.
Comparison expressions enable us to execute code only if certain conditions are met.
We use the keyword if, a colon, and an indented code block. Similar to function definition syntax, the if statement controls execution of the indented block.
After the keyword if is a conditional expression. If the expression evaluates to True, the controlled block runs:
if_true.py
this is controlled by the if statement
this is outside the if statement
If the expression does not evaluate to True, the controlled block doesn’t run:
if_false.py
this is outside the if statement
The simple True and False above are just to illustrate how if statements work. Any valid conditional expression can come after the if keyword:
if_statement.py
this is outside the if statement
The parentheses are optional, but they help organize the code. Another example:
two_ifs.py
Trace through the execution. With x = 2, line 3 will not run (because x > 3 is False), and line 6 does run (because x < 3 is True).
Try editing the code and changing the value of x. What happens with x set to 0. Why?
else and elifThe if keyword can be grouped with other keywords to executed code when the expression after the if is False:
With an if-else group, the code controlled by the else executes if the conditional expression for the if statement is not True. Exactly one of the two will execute.
Trace through the execution:
It’s common to want to perform another conditional check after the first check. Conditionals can be nested in Python:
if_else.py
Instead of nesting, however, we can use the conditional keyword elif (“else if”):
if_else.py
Rules for if-elif-else statements:
if statement must come first
if includes a conditional expressionif will run if the expression is Trueelif statements come next
elif statements are optional (you can have zero)elif includes a conditional expressionelif will be checked if the statement before it was Falseelif runs if its expression is Trueelse (optionally) is last
else does not have a conditional expressionelse was False, the else runsEach statement and expression is evaluated in order. As soon as one expression is True (or we the else is reached), the code block it controls will run, and the group of statements is exited.
A function can have multiple return statements, but remember that the function ends the first time any return statement is reached.
An example. This function returns True if the input is an integer with multiple digits, otherwise it returns False.
multiple_return.py
Note that this program has no printed output, because there are no calls to print.
Conditional expressions can be combined and modified with three additional logic operators: and, or, and not.
and operator will evaluate to True if both sides of the and are True.A |
B |
A and B |
|---|---|---|
True |
True |
True |
True |
False |
False |
False |
True |
False |
False |
False |
False |
or operator will evaluate to True if either (or both) sides of the or are True.A |
B |
A or B |
|---|---|---|
True |
True |
True |
True |
False |
True |
False |
True |
True |
False |
False |
False |
not operator reverses any boolean coming after it.We can look at examples of these expressions using the interpreter:
These evaluate to bools - which means they can be used with conditionals!
while LoopWe have used if statements to execute a block of code once if a condition is met.
The while loop extends this functionality and executes a block of code multiple times based on a condition being met.
The syntax is similar: the keyword while, followed by a condition, followed by a colon.
Unlike the if statement, which executes code once and then moves on, the while loop continues to execute as long as the condition is met:
True, the controlled block runs.This makes it very important to change something about the conditional expression during the loop. In the example above, x is increased, and the condition is checking if x is less than some value. By increasing x, we guarantee that the loop will eventually end.
This loop will run “forever:”
In practice, infinite loops will usually get stopped by your computer, or you will run out of memory, or get some other kind of error. You may need to manually terminate the loop, either by pressing Control+C or clicking a red “stop” button in your editor.
Because we subtract from x each iteration, x will always be less than 4.
Loops make performing some operation over a large number of values very simple. We could sum integers from 0 through 10:
infinite_loop.py
To perform the same computation on integers from 0 to one million, just change last_value to 1000000.
Python includes a few shortcuts that make our lives easier when performing common tasks. They’re optional, but useful.
+= operator simultaneously adds and assigns
x = x + 1 can be rewritten x += 1-=, *=, and \= operators1_000_000 is the same as 1000000, but it’s easier for humans to read1,000,000 means something in Python, but it does not mean “one million”
23_45 (the same as 2345), but that might be harder to read, not easierHere’s the simple loop rewritten with +=:
All of these shortcuts work with numbers; the += shortcut will work with strings as well.
for LoopBasic while loop syntax consists of three parts:
while statement with a condition related to that variablebasic_while.py
There are other ways to use while loops, but this way is very common.
The case of needing to iterate over an ordered collection of numbers is so common that Python has a specific way to do this: the for loop. The syntax is very simple:
for followed by a spaceinrange function, which creates a sequenceA sequence?
range(n) creates the sequence \(0, 1, 2 ,..., n-1\)range(5) creates sequence 0, 1, 2, 3, 4for loop iterates through the sequence
Trace through this for loop. It does the exact same thing as the while loop we just saw:
The range collection does not need to start at 0. If you pass two arguments to range, the first argument is the starting value, and the second is the stop-before value.
range(2, 6) starts at 2 and stops before 6
2, 3, 4, 5range(-2, 4) starts at -2 and stops before 4
-2, -1, 0, 1, 2, 3range(0, 5) is the same as range(5)
If you pass three arguments to range, the first is the starting value, the second is the stop-before value, the third is the spacing:
range(1, 6, 2) starts at 1, stops before 6, and has a spacing of 2
1, 3, 5range(10, 5, -1) starts at 10, stops before 5 and has a spacing of -1
10, 9, 8, 7, 6range(0, 5, 1) is the same as range(5)
while vs. forfor loops are simpler to writefor loop can be done with a while loop
for loopwhile loopThe print function can take multiple arguments to perform more ‘advanced’ printing. Print statements are very useful for writing and debugging loops.
The arguments can be any type (they do not need to be converted to strings).
By default, at the end of a print statement, the output advances to the next line. This “end” behavior can be overridden with a keyword argument, end=.
This example combines many of these concepts:
running_sum.py
Just like conditionals, loops can be nested within each other:
i and j change over the course of the loop
Write a function two_four that takes one argument, a number, and prints whether or not the number is between 2 and 4 (inclusive of 2 and 4):
two_four(5) results in printed output “5 is not between 2 and 4”two_four(3.1) results in printed output “3.1 is between 2 and 4”practice1_4_1.py
Hint: The comments in the code above outline the form of code that implements the function.
Implement the function two_four with the exact same behavior, using a different set of conditional statements.
Write a function that takes an argument, which could be a number or a string.
If the argument is a string, return the string "It's a string."
If the argument is a number, check if the number is positive.
"It's a positive number.""It's a negative number."0.Write a function that takes as argument a number and rounds that number to the closest int.
Do this without using Python’s built-in round function.
Return the result.
Write a program that uses a while loop to sum the integers between 1 and 20 (including 1 and 20).
(You should get 210 as the result).
After you have it working, rewrite the program to use a for loop instead.
Write a function sum_below that takes an integer argument and returns the sum of all integers between 1 and the argument, not including the argument.
sum_below(20) would return 190sum_below(15) would return 105You can assume the argument will always be a positive integer.
Write a function sum_skip that takes two integer arguments. Your function should sum all integers less (but including) than the first argument, skipping the second argument.
sum_skip(5, 4) would return 11 (\(1 + 2 + 3 + 5\), because 4 was skipped)sum_skip(6, 3) would return 18 (\(1 + 2 + 4 + 5 + 6\), because 3 was skipped)sum_skip(4, 6) would return 10 (\(1 + 2 + 3 + 4\), nothing is skipped because 6 is not part of the sum)You can assume the argument will always be a positive integer.
Note: There is an “easy” way to solve this, by subtracting the second argument from the sum. Try solving this problem a different way.
Write a function round_three that takes an argument, a number, and rounds up to the nearest multiple of three, returning that value.
round_three(4.2) returns 6round_three(3) returns 3round_three(-2) returns 0Hint: You can check if a number is divisible by three by using the % operator: if x % y is equal to zero, x is evenly divisible by y.
Homework problems should always be your individual work. Please review the collaboration policy and ask the course staff if you have questions. Remember: Put comments at the start of each problem to tell us how you worked on it.
Double check your file names and printed output. These need to be exact matches for you to get credit.
Write a function smart_root that takes one argument, a number.
If the number is not negative, return the number’s square root, rounded down to the nearest int.
If the number is negative, return string 'The number is negative'
Examples:
smart_root(4) returns int '2'smart_root(2) returns int '1'smart_root(1) returns int '1'smart_root(-1) returns string 'The number is negative'Submit as smart_root.py.
Write a function check_square that takes one argument, a positive integer:
If the integer is a perfect square, return string 'Perfect square!'
Otherwise, return string 'Not a perfect square.'
check_square(4) returns string 'Perfect square!'
check_square(9) returns string 'Perfect square!'
check_square(10) returns string 'Not a perfect square.'
(A perfect square is a number that is the product of an integer multiplied by itself.)
Submit as check_square.py
math.sqrt always returns a floatmath.sqrt function on a perfect square will return a float that is equal to an integer
math.sqrt(9) returns 3.0math.sqrt on a number that isn’t a perfect square returns a float not equal to an integer
math.sqrt(10) returns 3.1622776601683795The function polarity is intended to check if a number is positive, negative, or zero, and return the result in the following format:
polarity(4) returns string 'Positive.'polarity(-2) returns string 'Negative.'polarity(0) returns string 'Zero.'Here is the draft function. It does not quite work. Fix it!
polarity.py
Submit as polarity.py.
Write a function positioner that takes as argument a number. Your function should compare this number to three other numbers: 3, 13, and 31, and return the result of the comparison as a string. The returned string should have the numbers in order, separated by spaces. Here are examples of the format:
positioner(2) returns string '2 3 13 31'positioner(1) returns string '1 3 13 31'positioner(15) returns string '3 13 15 31'positioner(200) returns string '3 13 31 200'positioner(13) returns string '3 13 13 31'The input argument is printed in numerical order along with 3, 13, and 31. There are spaces between each pair of numbers; there is no space at the end of the sequence.
Submit as positioner.py.
Write a function closer_to_zero that takes as argument a number.
Examples:
closer_to_zero(4) returns 3closer_to_zero(-2) returns -1closer_to_zero(0) returns 0Submit as closer_to_zero.py.
Write a function sequence_skip that takes two arguments, both integers.
Type Hint: Your function should return a string.
sequence_skip(5, 2) returns string '0 1 3 4'sequence_skip(4, 3) returns string '0 1 2'sequence_skip(6, 1) returns string '0 2 3 4 5'sequence_skip(4, 5) returns string '0 1 2 3'Submit as sequence_skip.py.
Write a function sequence_string that takes one argument, an integer, and returns a string.
sequence_string(2) returns string '2 3 4 5'sequence_string(7) returns string '7 8 9 10'sequence_string(15) returns string '15'Submit as sequence_string.py
Write a function greatest_factor that takes one argument, an integer, and returns the largest integer, smaller than the argument, that the argument divides into evenly. (The return value does not need to be prime.) The argument will always be greater than one.
greatest_factor(9) returns integer 3greatest_factor(20) returns integer 10greatest_factor(24) returns integer 12greatest_factor(7) returns integer 1Submit as greatest_factor.py
For greatest_factor, use a loop to check numbers smaller than the argument: