End of class exercises#

Exercise 1#

In the cell below, define a function of two variables, call it, mymax, which returns the maximum of two real numbers \(a\) and \(b\).

NOTE In class, we introduced the max function. Here you should write your own function to do the same. DO NOT use max itself (or anything similar) to do this.

Exercise 2#

Predict (by writing on paper) what the

following expressions must evaluate to:

  • True and True

  • True and False

  • False and False

  • False and True

If you are not sure you can try printing them in the cell below.

This is called a “truth table”. What about the truth table for “or”:

  • True or True

  • True or False

  • False or False

  • False or True

Verify in the cell below

Exercise 3#

What do the following expressions evaluate to? Try to figure this out in your head first and then print the values of the variables defined in the cell below.

x1 = 1 < 2 and 2 < 3
x2 = 1 < 2 and 2 > 3
x3 = 1 > 2 and 2 > 3
x4 = 1 > 2 and 2 < 3

Exercise 4#

Evaluate (Shift+Enter) the cell below:

x= int(input('Please input an integer: '))
if x%3 == 0:
    print('The number is a multiple of 3')
else:
    print('The number is not a multiple of 3')
---------------------------------------------------------------------------
StdinNotImplementedError                  Traceback (most recent call last)
Input In [2], in <module>
----> 1 x= int(input('Please input an integer: '))
      2 if x%3 == 0:
      3     print('The number is a multiple of 3')

File /opt/homebrew/Caskroom/miniconda/base/envs/pycbc_test/lib/python3.9/site-packages/ipykernel/kernelbase.py:1190, in Kernel.raw_input(self, prompt)
   1188 if not self._allow_stdin:
   1189     msg = "raw_input was called, but this frontend does not support input requests."
-> 1190     raise StdinNotImplementedError(msg)
   1191 return self._input_request(
   1192     str(prompt),
   1193     self._parent_ident["shell"],
   1194     self.get_parent("shell"),
   1195     password=False,
   1196 )

StdinNotImplementedError: raw_input was called, but this frontend does not support input requests.

This introduces the input command, to take a value from the command line. Make sure that you understand every single line of the above code. Discuss with us if you don’t! Remember, a lot of learning with python and computing in general is learning by trying, so feel free to test out what happens if you tweak this etc.

WARNING input is a useful command for these interactive notebooks, but will very rarely be of use in data science, where one would read in large datasets (which we’ll show later on). NEVER use this command in the coursework questions. We will always provide inputs to you there, using this will just make things fail!!

Exercise 5#

In the cell below, write a code that reads an integer from the keyboard (your input). If this input is divisible by \(2\) and \(3\) display the following:

  • This number is divisible by 2 and by 3!

Now extend your answer to do the following:

In the cell below, write a code that reads an integer from the keyboard. You need to include conditions which display the following statements if they are true:

  • “This number is divisiable by \(2\) and \(3\).”

  • “This number is divisiable only by \(2\).”

  • “This number is divisiable only by \(3\).”

  • “This number is not divisiable by \(2\) and \(3\).”

You need one if condition, two elif conditions and one else condition.

Exercise 6#

Define a function so that it returns an absolute value of an input. We will define this as:

  • If x is greater than or equal to 0, return x

  • Otherwise, return -x

In concise maths notation this is written as

\[\begin{split}f(x) = |x| = \begin{cases}x & \mbox{if } x \geq 0 \\ -x & \mbox{if } x<0 \end{cases}.\end{split}\]

Name it abs_val.

Hint: Use if, else conditionals.

Exercise 7#

Define a function of two numbers (numerical variables) that returns the distance between these numbers (ie. what is the absolute value of the difference of the two numbers). Please use your function abs_val from the exercise above. Test this for some example input.

Exercise 8#

In the cell below, write a code that reads a letter of the alphabet from the keyboard. Then send that entered letter to a function, if the entered letter is a, e, i, o or u then you should display a message indicating that the entered letter is a vowel. If the user enters y then your program should display a message indicating that sometimes y is a vowel, and sometimes y is a consonant. Otherwise your program should display a message indicating that the letter is a consonant.

Exercise 9#

In the cell below, write a function that determines the name of a shape from its number of sides. Take the number of sides as an input and then return the appropriate name of the shape. Your function should support shapes with anywhere from \(3\) up to (and including) \(10\) sides.

We have

  • Triangle - \(3\) Sides, Square - \(4\) Sides

  • Pentagon - \(5\) Sides, Hexagon - \(6\) sides

  • Heptagon - \(7\) Sides, Octagon - \(8\) Sides

  • Nonagon - \(9\) Sides, Decagon - \(10\) Sides

Exercise 10#

In the cell below, define the following function, $\( H(x) = \begin{cases} 1 & \mbox{if } x\geq 0 \\ 0 & \mbox{if } x< 0 \end{cases}.\)$

(That is, a function that:

  • Takes one input variable, called x

  • Returns 1 if x is bigger than or equal to 0.

  • Return 0 if x is less than 0. )

and test for some example input values

Exercise 11#

In the cell below, define the following three functions, $\( x(R, \theta, \phi) = R \cos \phi \sin \theta \)\( \)\( y(R, \theta, \phi) = R \sin \phi \sin \theta \)\( \)\( z(R, \theta, \phi) = R \cos \theta \)$ and test for some example input values.

Could you write this as a single function, returning \(x\), \(y\) and \(z\)?

Exercise 12#

In the cell below, add a new function definition for a function \(g(x) = x^3 -4x + 2\). Then print the following:

  • \(g(-4)\),

  • \(g(g(1))\),

  • \(g(g(0))\).

Exercise 13#

In the cell below, define a function called rectangle_area that takes two varables \(w\) and \(h\) as an input and returns the area of the rectangle with width \(w\) and height \(h\). Test your function by printing a couple of examples.

Exercise 14#

A triangle can be classified based on the lengths of its sides as equilateral, isosceles or scalene. All 3 sides of an equilateral triangle have the same length. An isosceles triangle has two sides that are the same length, and a third side that is a different length. If all of the sides have different lengths then the triangle is scalene. In the cell below, write a code that reads lengths of 3 sides of a triangle from the keyboard and displays a message indicating the type of the triangle.

Exercise 15 (difficult)#

Write a function which determines if a float input is a “happy number”. We will define a happy number as:

  • One that is closer to the integer above it, than the integer below it.

  • If you take the number, convert it to an integer (with int) and square it, is a multiple of 3.

  • If you multiply the number by 9 the resulting number has a 9 in it before the decimal point.

Are any of these “happy numbers”?

  • 4.59

  • 4.05

  • 12.35

  • 15.45

  • 99.001

Exercise 16#

WARNING This may sound challenging, but the coding here isn’t as bad as some of the previous exercises. Often a challenge in coding is wading through some complex sounding description to break it down into simple, step-by-step things to code. This is a good example of that:

A quadratic polynomial has a form \(p(x)= ax^2 + bx+c\), where \(a, b\) and \(c\) are constants and \(a\) is non-zero. We say that \(x_0\) is a root of \(p\) if \(p(x_0)=0\). A discriminant of a polynomial is a polynomial function of its coefficients, which allows deducing some properties of the roots without computing them. For example, the discriminant of \(p\) is \(\Delta= b^2 - 4ac\). In the cell below, write a code that reads the coefficients of \(p\), that is, \(a\), \(b\) and \(c\) from the keyboard. Then depending on the value of \(\Delta\) display if \(p\) has two distinct roots, one double root or no real roots.

Recall that if

  • \(\Delta >0\) then \(p\) has two distinct real roots,

  • \(\Delta = 0 \) then \(p\) has one double root,

  • \(\Delta <0\) then \(p\) has no real roots.