(This is a **mock test**. The real Class Test 1 will look similar and will be held in Week 2.)

**Aim:**

- To help you learn enough about Python to enjoy the remainder of this course.

**How it works:**

- Complete the notebook below, as follows. First, click on a question, then from the menu select Insert -> Insert Cell Below. From the dropdown box (next to the "stop" symbol) choose whether you wish to insert 'Code' or 'Markdown' (i.e. text). Save regularly!
- Press Shift-Enter to execute the code in a cell.
- Submit via http://mas212.group.shef.ac.uk/uploads by 5pm on Mon 29th Oct.
- Your lecturer will mark each question as either 2 (good), 1 (needs revision), 0 (not attempted/wrong). You will then be given one chance to revise your answers and resubmit.
- This is an open-book test, which means you may consult books, notes and internet resources. However, copy-and-pasting is
**strongly discouraged**, and would reflect badly on a Level 2 University of Sheffield student.*Please give answers in your own words.*

**Key Resources:**

- Chapter 1 in https://scipy-lectures.github.io/

**Q. Python is case-sensitive: True or false?**

True

**Q. Python has four numeric types -- what are they?**

`int`

, `float`

, `long`

, and `complex`

.
Python 3.4 has only three, as the `long`

type has been removed, as `int`

s may now be arbitrarily large.

**Q. Describe in your own words the int and float data types.**

`int`

is a representation of an integer, i.e., a whole number.
`float`

is a representation of a real number. In Python, as in other languages, this is represented internally by a *mantissa* and *exponent* (e.g., $1.2345$ may be represented as $12345 \times 10^{-4}$).

N.B. For real numbers with arbitrary precision, use the `decimal`

module.

**Q. Python has several container types. Give three examples.**

Any three of: `list`

, `string`

, `dict`

, `set`

and `tuple`

.

Note that you can use `type()`

to find out the type of any object.

In [3]:

```
print(type([0, 1, 2])) # list
print(type("I love tests!")) # str (string)
print(type({'pi': 3.1415926, 'e': 2.7182818, 'gamma': 0.5772157})) # dict (dictionary). Here, mathematical constants.
print(type(set([0, 2, 0, -1, 2]))) # set (a set is like a list with no ordering & no duplicates)
print(type((1,2))) # tuple
```

**Q. What does mutable mean? Give an example of mutable and unmutable sequences.**

`list`

is mutable: it can be modified in-place. A tuple is *immutable*: attempting to change it will cause an error. For example,

In [4]:

```
a = [1, 2, 3] # list
a[0] = 5
print(a)
```

In [5]:

```
b = (1,2,3) # tuple
b[0] = 5 # will throw an error
```

Strings are also immutable. In order to change a string, a new string must be created.

For example, in the code below, the function `replace`

(which is a member of the `str`

class) creates a new string, which is assigned to `d`

.

In [6]:

```
c = "Hello everyone."
d = c.replace("Hello", "Goodbye")
print(c + " " + d)
```

2. Simple Python code

(Please answer the following questions in "code" cells).

**Q. Python as a calculator: Calculate $3 + 4$, $3 \times 4$, $3 / 4$, $3^2 + 4^2$ and $(3 + 4i)^{3}$.**

In [7]:

```
[3+4, 3*4, 3 / float(4), 3**2 + 4**2, complex(3,4)**3]
```

Out[7]:

**Q. Use for loop to find the sum-of-squares $1 + 4 + 9 + \ldots + 100$**

In [9]:

```
tot = 0
for i in range(1,11): # i in the range 1 to 10
tot += i**2
print("The answer is %d" % tot) # (If this syntax is unfamiliar, read up on string formatting)
```

**Q. Make a list of square numbers $[1, 4, 9, \ldots, 100]$ and find the sum another way**

In [10]:

```
l = [i**2 for i in range(1,11)]
sum(l)
```

Out[10]:

**Q. Print the value of $\pi$ to 10 decimal places. (Hint: first import the "math" package).**

In [12]:

```
import math
print("pi = %.10f" % math.pi)
```

In [13]:

```
fib = [1,1]
for k in range(18):
fib.append(fib[-1]+fib[-2])
print(fib)
```

**Q. Print the value of Pi to 20 decimal places. (Hint: import the math package).**

In [14]:

```
import math
print("%.10f" % math.pi)
```

In [15]:

```
def divisors(N):
return [i for i in range(1,N+1) if N % i == 0]
divisors(2014)
```

Out[15]:

**Q. Calculate all perfect numbers less then 10000.**

In [16]:

```
[i for i in range(2,1000) if sum(divisors(i)[:-1]) == i]
# Note that "proper divisors" do not include the number itself.
```

Out[16]:

3. String processing

In [17]:

```
s = "The horse has a long neck"
```

**Q. How many characters are in this string?**

In [18]:

```
len(s)
```

Out[18]:

**Q. Replace the word "horse" with "giraffe".**

In [19]:

```
print(s.replace("horse", "giraffe"))
```

In [21]:

```
print(s[::3]) # every third character
print(s[len(s)//2:]) # second half of string
print(s[::-1]) # reversed string
```

**Q. How many times does the letter "e" appear in this string?**

In [22]:

```
s.count("e")
```

Out[22]:

**Q. Which words in the sentence contain the letter "e"?**

In [23]:

```
[w for w in s.split(" ") if "e" in w]
```

Out[23]:

4. A slightly harder question

In [24]:

```
s2 = "Ju jt b usvui vojwfstbmmz bdlopxmfehfe uibu b tjohmf nbo jo qpttfttjpo pg b hppe gpsuvof nvtu cf jo xbou pg b xjgf"
```

**Q. Decipher the string above. From which novel is it taken?**

Note that characters may be turned into integers (ASCII codes) using `ord()`

and back again using `chr()`

.

`k`

steps. Shifting by -1 does the trick here. It's from *Pride and Prejudice* by Jane Austen.

In [27]:

```
def caesar(s, n):
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUV"
l = [chr(ord(c)+n) if c in alphabet else c for c in list(s)]
return "".join(l)
caesar(s2, -1)
```

Out[27]:

In [ ]:

```
```