4.5. Exercises

  1. Use a for statement to print 10 random numbers.

  2. Repeat the above exercise but this time print 10 random numbers between 25 and 35.

4.5.1. Contributed Exercises

Q-1: After completing the reading, what concepts are still unclear to you? If nothing is unclear, what did you find most interesting?

    Q-1: (TEST) The correct code to generate a random number between 1 and 100 (inclusive) is:

  • prob = random.randrange(1, 101)
  • This will generate a number between 1 and 101, but does not include 101.
  • prob = random.randrange(1, 100)
  • This will generate a number between 1 and 100, but does not include 100. The highest value generated will be 99.
  • prob = random.randrange(0, 101)
  • This will generate a number between 0 and 100. The lowest value generated is 0. The highest value generated will be 100.
  • prob = random.randrange(0, 100)
  • This will generate a number between 0 and 100, but does not include 100. The lowest value generated is 0 and the highest value generated will be 99.

In statistical physics, it is common to use Stirling’s approximation for \(N!\),

\[N!\approx N^N e^{-N} \sqrt{2\pi N}.\]

Obtain an integer from the user, assign it to N, and print out, in order, \(N!\), Stirling’s approximation, and the relative percent error. The relative percent error is calculated as

\[\text{error} = \left| \frac{\text{approx} - \text{exact}}{\text{exact}} \right| 100\%.\]

For a right triangle we have

\[\tan(\theta) = \frac{\text{opp}}{{adj}}\]

Compute and print \(\theta\) for

\[\begin{align} \left(\text{opp}=1,\text{adj}=1\right), \left(\text{opp}=1,\text{adj}=-1\right), \left(\text{opp}=-1,\text{adj}=1\right),\text{and} \left(\text{opp}=-1,\text{adj}=-1\right). \end{align}\]

Hint: use the function atan2() instead of atan().

Use the double angle formula,

\[\sin(2\theta) = 2\sin(\theta)\cos(\theta),\]

to compute and print

\[\sin(\pi/4)\]

    Q-1: Which is the best way to import the math module so you can use the exp() function?

  • import math
  • Correct! This will make it obvious to anyone who reads your code when you use something from the ``math`` module.
  • from math import exp
  • This imports only the ``exp()`` function and puts it in the global namespace. This can make it difficult to tell where this function comes from.
  • from math import *
  • This imports everything from ``math`` and puts it in the global namespace. This can make it difficult to tell when the ``math`` module is being used.
  • import math as m
  • Don't change the names of modules unless it is the convention for that module. This makes your code harder to read.

    Q-1: Which of the following functions are part of the math module?

  • exp()

  • abs()

  • int()

  • sin()

  • fabs()

  • pi

You have attempted of activities on this page
Next Section - 5. Python Turtle