Python Introduction Exercises¶

Programming for Data Science Bootcamp

Exercise 1¶

Define a string with a length >= 6 and print:

  • the first three characters of the string
  • the last three characters of the string
In [2]:
mystr = 'python'
len(mystr) >= 6
Out[2]:
True
In [3]:
mystr[:3]
Out[3]:
'pyt'
In [4]:
mystr[-3:]
Out[4]:
'hon'

Exercise 2¶

Create a new list and assign three values to it.

Then print the second element from the list.

In [11]:
mylist = []
mylist.append('first')
mylist.append('second')
mylist.append('third')
mylist[1] 
Out[11]:
'second'
In [12]:
mylist = []
mylist += ['first']
mylist += ['second', 'third']
mylist[1]
Out[12]:
'second'
In [13]:
mylist = ['first','second','third']
mylist[1]
Out[13]:
'second'
In [14]:
mylist2 = ['foo']
In [15]:
mylist2[1] = 'bar'
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
Cell In[15], line 1
----> 1 mylist2[1] = 'bar'

IndexError: list assignment index out of range

Exercise 3¶

Create to a tuple with three values.

Then, try to append a fourth value.

In [16]:
mytuple = 1, 2, 3
In [17]:
mytuple = (1, 2, 3)
In [18]:
mytuple = tuple([1, 2, 3])
In [19]:
mytuple.append(4) 
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[19], line 1
----> 1 mytuple.append(4) 

AttributeError: 'tuple' object has no attribute 'append'

Exercise 4¶

Assign a string value to a scalar variable.

Assign three string values to a set.

Check if the scalar is in the set.

In [20]:
val = 'ERROR'
levels = {'WARN','ERROR','CRITICAL'}
In [21]:
val in levels
Out[21]:
True
In [22]:
levels = {'WARN','ERROR','CRITICAL','WARN','ERROR','CRITICAL'}
In [23]:
levels
Out[23]:
{'CRITICAL', 'ERROR', 'WARN'}

Exercise 5¶

Create a dictionary containing at least three key-value pairs.

Use get() to index into the dictionary with one of the keys to extract the corresponding value.

Then, store the keys in a list and print the list.

In [24]:
name_age = {
    'greg': 15, 
    'annabel': 22, 
    'joaquin': 19
}
In [26]:
print("name_age['joaquin'] =", name_age.get('joaquin'))
name_age['joaquin'] = 19
In [27]:
names = list(name_age.keys())
In [29]:
print('names:', names)
names: ['greg', 'annabel', 'joaquin']
In [30]:
type(name_age.keys()), type(names)
Out[30]:
(dict_keys, list)

Exercise 6¶

Convert the following sentence into a set of lowercase words sorted alphabetically.

Do not include the punction mark in the resulting set.

"The quick brown fox jumped over the lazy dogs."

In [31]:
mystring = "The quick brown fox jumped over the lazy dogs."
In [36]:
mystring1 = mystring.replace('.', '')
mystring2 = mystring1.lower()
mystring3 = mystring2.split()
mystring3
Out[36]:
['the', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dogs']
In [37]:
myset1 = set(mystring3)
myset2 = sorted(myset1)
myset2
Out[37]:
['brown', 'dogs', 'fox', 'jumped', 'lazy', 'over', 'quick', 'the']
In [39]:
sorted(set(mystring.replace('.', '').lower().split()))
Out[39]:
['brown', 'dogs', 'fox', 'jumped', 'lazy', 'over', 'quick', 'the']

Exercise 7¶

Compare the lengths of the preceding list and set.

If not equal, give the difference.

In [40]:
mylist = mystring.replace('.', '').lower().split()
myset = set(mylist)
In [41]:
len(mylist) == len(myset)
Out[41]:
False
In [42]:
abs(len(mylist) - len(myset))
Out[42]:
1

Exercise 8¶

Define three variables of any type.

Use an f string to print a string containing each variable name followed by its value, using comma separators between the pairs.

For example:

epoch 1, mode TRAIN, ...

In [43]:
epoch = 1
mode = "TRAIN"
loss = 0.46

print(f"epoch {epoch}, mode {mode}, loss {loss}")
epoch 1, mode TRAIN, loss 0.46

Exercise 9¶

Define two variables, assigning them floating point values.

Write an expression using an operation on the two variables that will produce a value that may be cast as an integer.

Next, use a logical operation that uses the integer that evaluates to False. Print the result with print()

In [44]:
var1 = 1.5
var2 = 20.5
var3 = int(var1 // var2)
In [45]:
var1 // var2
Out[45]:
0.0
In [46]:
var3
Out[46]:
0
In [47]:
test = var3 < 0
In [48]:
print(test)
False

Exercise 10¶

Write a Python program to print the input string in the format of the output:

Input:

“Twinkle, twinkle, little star, How I wonder what you are! Up above the world so high, Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what you are”

Output:

Twinkle, twinkle, little star,
    How I wonder what you are! 
    	Up above the world so high,   		
    	Like a diamond in the sky. 
Twinkle, twinkle, little star, 
    How I wonder what you are

Solution 1¶

In [49]:
print("Twinkle, twinkle, little star, \n\tHow I wonder what you are! \n\t\tUp above the world so high, \n\t\tLike a diamond in the sky. \nTwinkle, twinkle, little star, \n\tHow I wonder what you are!")
Twinkle, twinkle, little star, 
	How I wonder what you are! 
		Up above the world so high, 
		Like a diamond in the sky. 
Twinkle, twinkle, little star, 
	How I wonder what you are!

Solution 2¶

In [50]:
msg = """
Twinkle, twinkle, little star, 
\tHow I wonder what you are! 
\t\tUp above the world so high, 
\t\tLike a diamond in the sky. 
Twinkle, twinkle, little star, 
\tHow I wonder what you are!
"""
In [51]:
print(msg)
Twinkle, twinkle, little star, 
	How I wonder what you are! 
		Up above the world so high, 
		Like a diamond in the sky. 
Twinkle, twinkle, little star, 
	How I wonder what you are!

Exercise 11¶

Compute a and b as follows:

a = 0.15 + 0.15
b = 0.1 + 0.2

Test to see if a and b are equal.

In [ ]:
a = 0.15 + 0.15
b = 0.1 + 0.2
Running cells with 'Python 3.13.1' requires the ipykernel package.

Run the following command to install 'ipykernel' into the Python environment. 

Command: '/opt/homebrew/bin/python3 -m pip install ipykernel -U --user --force-reinstall'
In [53]:
a == b
Out[53]:
False
In [54]:
a, b
Out[54]:
(0.3, 0.30000000000000004)

What is going on? Floating point comparisons are unreliable because of the way the computer stores their values.

Accoring to The Floating-Point Guide, "Due to rounding errors, most floating-point numbers end up being slightly imprecise."