# Concurrency-1-Introduction

Last updated: March 4th, 2021

### Welcome!¶

This is a Jupyter Notebook. If you're not familiar with it, don't worry, because by the end of this course you'll be very used to them. A Jupyter Notebook let's you execute Python code in a visual-friendly environment. Try executing the following code:

In [5]:
2 + 2

Out[5]:
4

You can create cells and move them around to write your own code. Try with the following empty cells:

In [ ]:


In [ ]:



If an error happens, don't worry, it's just a red message, it'll let you debug it. Let's cause an error and fix it:

In [7]:
# fahrenheit to celsius calculator
temp = input("What's the temperature in F:")

print("The temperature in C is:")
print((temp - 32) * 5/9)

What's the temperature in F:80
The temperature in C is:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-4ac8e2a7d745> in <module>
3
4 print("The temperature in C is:")
----> 5 print((temp - 32) * 5/9)

TypeError: unsupported operand type(s) for -: 'str' and 'int'

😱 An error occurred! Don't you worry, the error message is there to help us. The issue is that we're not transforming the temperature value to an int. Let's fix it:

In [8]:
# fahrenheit to celsius calculator
temp = input("What's the temperature in F:")

temp = int(temp)
print("The temperature in C is:")
print((temp - 32) * 5/9)

What's the temperature in F:80
The temperature in C is:
26.666666666666668


Wasn't this about writing concurrent Python programs? Yes, it is! Let's do a sneak preview of Python threads and play a little bit with them:

In [9]:
import time
import random

In [10]:
random.randint(0, 5)

Out[10]:
1
In [11]:
def sleep_and_print(name, times=5):
for _ in range(times):
print(f'{name} sleeping...')
time.sleep(random.randint(0, 5))

In [12]:
sleep_and_print('Maria')

Maria sleeping...
Maria sleeping...
Maria sleeping...
Maria sleeping...
Maria sleeping...

In [13]:
t1 = threading.Thread(target=sleep_and_print, args=('Maria', ))

In [14]:
t1.start()
t2.start()

Maria sleeping...
John sleeping...
Maria sleeping...
John sleeping...
Maria sleeping...
Maria sleeping...John sleeping...

John sleeping...
Maria sleeping...John sleeping...


In [ ]:
import string

In [ ]:
string.ascii_letters

In [ ]:
print?


#### To the terminal!¶

We've written a simple python program that you can execute using the terminal associated with this lesson. Go ahead and try it out. Open the terminal and issue the following command: python thread_writers.py