CSCI 235, Lab Exercise 5, Basics of Python
Deadline: 13.10.2023 at 11PM
Solutions must be submitted into Moodle as a single text 2ile, with name [Link],
into Moodle. Don’t use an archiver.
Your 2ile must contain two functions de2initions, sine and collatz.
Goal of this exercise is that you learn how to run a Python program, that you
become familiar with the lay out of a Python program, and that you learn some
basic functions of Python.
Make sure that you are using Python version 3.10 or higher.
1. Write a function that computes the trigonometric sine function by means
of the Taylor expansion:
Test your implementation for real numbers and for complex numbers. You
!"#$
can stop when the factor (!"#$)! becomes very small, or repeat up to a high
number, for example 50.
Make sure that your function starts with def sine(x) : and that it can
be called as [Link] from the Python interpreter.
>>> [Link]( 0.1 )
0.09983341664682817
>>> [Link]( 30 * 3.1415926536 / 180 )
0.5000000000014734
>>> [Link]( 0.5 - 0.3j )
(0.5011619801599463-0.2672416992709515j)
2. The Collatz sequence is de2ined as follows: If n is even, then the next number
is n/2. If n is odd, then the next number is 3n + 1. For example, starting with
6 gives the following sequence:
6 ⇒ 3 ⇒ 10 ⇒ 5 ⇒ 16 ⇒ 8 ⇒ 4 ⇒ 2 ⇒ 1.
It is believed (but not proven) that every number reaches 1 eventually.
Your task is to write an interactive function (called collatz) that
repeatedly ask the user for a number greater than one. If the user types ’quit’,
1
’q’, or ’Q’ then the program stops. If the user types a number less or equal to
one, then the program must tell that the number is too small and ask for a
new number. If the number is greater than one, the program should show
the Collatz sequence for this number. Your function must start with def
collatz( ) : Here is an example:
>> [Link]( )
Please type a number greater than
one or ’quit’ to quit
6
Giving Collatz sequence for 6
iteration 1 results in 6
iteration 2 results in 3
iteration 3 results in 10
iteration 4 results in 5
iteration 5 results in 16
iteration 6 results in 8
iteration 7 results in 4
iteration 8 results in 2
iteration 9 results in 1
Please type a number greater than
one or ’quit’ to quit
1
you typed 1, which is not greater
than one Please type a number
greater than one or ’quit’ to quit q
goodbye
• It is convenient to use format in Python.
print( "{} is less than {}". format(1,2))will print 1
is less than 2.
• You can use input() to ask for input.
• Use // for division to make sure that the sequence stays integer.
• Checking if the input is a correct number seems to be tricky. The easiest
way is to call the int( ) function, which tries to convert a string into
an integer, and to catch the exception if it is thrown:
try:
inp = input(
) i = int( inp )
except
ValueError:
# it turns out that inp was not an integer.