Showing posts with label compound assignment operators. Show all posts
Showing posts with label compound assignment operators. Show all posts

Problem Solving With Python: Program 5

The problem statement:

We are tasked with displaying all the powers of 2 less than 1,000 along with a message describing the output.

The following is the expected approximate output of program 5:

  • 1
  • 2
  • 4
  • 8
  • 16
  • 32
  • 64
  • 128
  • 156
  • 512
  • These are all the powers of 2 less than 1000


The Solution:

def powers_of_two_less_than_one_thousand():
    power = 1
    while power < 1000:
        print(power)
        power *= 2
    print("These are all the powers of 2 less than 1000")


def equivalent_solution():

    power = 1
    print(power)
    power = power * 2
    print(power)
    power = power * 2
    print(power)
    power = power * 2
    print(power)
    power = power * 2
    print(power)
    power = power * 2
    print(power)
    power = power * 2
    print(power)
    power = power * 2
    print(power)
    power = power * 2
    print(power)
    power = power * 2
    print(power)
    print("These are all the powers of 2 less than 1000")


if __name__ == '__main__':
    powers_of_two_less_than_one_thousand()

In previous examples we saw how to use a for loop to write concise solutions that allowed us to reuse code that is written in the body of the loop. Our solution to the stated problem will also use a loop to reuse code, but it will not be a for loop because we are not interested in iterating over a list of predefined items. Instead, we use a while loop.

What is a while loop? 

A while loop allows us to continue processing code that is within the body of the loop until a condition is met or satisfied. The looping condition for our while loop is that the variable named power is less than the value of 1000. If this condition ever fails then the while loop is terminated.

How does a while loop work? 

The body of the loop is executed until the condition becomes false. The condition that is defined is evaluated for a boolean value of True or False at the beginning of each loop. The loop terminates once the evaluation of our conditional "sees" a value of False, else the looping continues. This implies that it is possible to program a while loop that never terminates and therefore runs forever. This condition is known as an infinite loop and is usually the result of a bug in our code or reasoning. We can create create the condition of an infinite loop by forgetting to multiply by 2 on each iteration of the loop.

Unraveling the while loop. 

If you are having difficulties understanding the code in this or any while loop then it is sometimes helpful to unravel the loop. We can gain greater visibility in the looping code by examining an equivalent solution that does not use any looping mechanism. That is, solve the solution in its entirety, or partially if the result is long, by not reusing code inside a loop. For example, the solution given with a while loop is equivalent to the code found in the equivalent_solution() function, (remember that power *= 2 is shorthand for power = power * 2).

Page with links to the entire series can be found here

Are you having any issues running or understanding the program? Please, add a comment explaining where you are stuck or where the tutorial is not clear so we can improve it.

Problem Solving With Python: Program 4

The problem statement:

Program 3 introduced an operator that increments the value of a variable by a desired amount, namely, the += operator. Recall that the use of this operator allowed us to replace this expression variable = variable + 1 with the following concise expression variable += 1. Because this operator first computes the sum of the existing variable value with the desired constant value (e.g. 1) and then assigns the sum to the same variable this operator is called a compound assignment operator. This is not the only compound assignment operator available in python that can be used to write concise code.

Given the following Python program, the task is to refactor the code to make it more concise with the use of compound assignment operators where applicable.

Given program:

def given_code():
    variable_1 = 10
    variable_2 = 10
    variable_3 = 10
    variable_4 = 10
    variable_5 = 10
    variable_6 = 10
    variable_7 = 10

    variable_1 = variable_1 + 3
    variable_2 = variable_2 - 3
    variable_3 = variable_3 * 3
    variable_4 = variable_4 ** 3
    variable_5 = variable_5 / 3
    variable_6 = variable_6 // 3
    variable_7 = variable_7 % 3

    print("Before Compound Operation Use:")
    for variable_i in [variable_1, variable_2, variable_3, variable_4, variable_5, variable_6, variable_7]:
        print("    Variable:", variable_i)


The following is the expected approximate output of program 4:

Before Compound Operations:
  • Variable: 13
  • Variable: 7
  • Variable: 30
  • Variable: 3.3333333333333335
  • Variable: 3
  • Variable: 1
After Compound Operations:
  • Variable: 13
  • Variable: 7
  • Variable: 30
  • Variable: 1000
  • Variable: 3.3333333333333335
  • Variable: 3


The Solution:

def refactored_code():
    variable_1 = 10
    variable_2 = 10
    variable_3 = 10
    variable_4 = 10
    variable_5 = 10
    variable_6 = 10
    variable_7 = 10

    variable_1 += 3
    variable_2 -= 3
    variable_3 *= 3
    variable_4 **= 3
    variable_5 /= 3
    variable_6 //= 3
    variable_7 %= 3

    print("After Compound Operation Use:")
    for variable_i in [variable_1, variable_2, variable_3, variable_4, variable_5, variable_6]:
        print("    Variable:", variable_i)


def program_4():
    given_code()
    refactored_code()


if __name__ == '__main__':
    program_4()


Arithmetic Operators:

  • + is used for addition.
  • - is used for subtraction.
  • * is used for multiplication.
  • ** is used for exponentiation. E.g.,  2**5 = 32 is read as 2 raised to the power of 5 or 2*2*2*2*2 = 32.
  • / is used for division. E.g., 1/2 = 0.5
  • // is used for floor division. E.g., if 8/3 = 2.666... then 8//3 = 2. I.e., the decimal point (.) and everything to the right of it is dropped.
  • % is used for computing the remainder of a division operation. E.g., 8%3 = 2.


Page with links to the entire series can be found here

Are you having any issues running or understanding the program? Please, add a comment explaining where you are stuck or where the tutorial is not clear so we can improve it.