Concurrency-1-Introduction

Last updated: January 9th, 20212021-01-09Project preview

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

Python Concurrency with Threads

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 threading
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', ))
t2 = threading.Thread(target=sleep_and_print, args=('John', ))
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

Notebooks AI
Notebooks AI Profile20060