For some reason pyautogui.hotkey('win', 'l') doesn't work. That's why I wrote a code that will automatically lock the pc if the code is run. Run the code or squeeze those few lines in your existing code then use it.
full tutorial on https://www.instructables.com/id/Simple-Python-Code-to-Auto-Lock-Your-Computer
Updated to make a complete app: https://github.com/ashraf-minhaj/ChikonEye_a-third-eye-app-which-protects-your-work-from-peepers.
*Run the code like this in you command prompt or powershell
python pyautogui.lock.py
*squeezze or add inside your code
if your condition: lock the pc
Note: To make this code work you must need to install python on your computer. After installing python install pyautogui
pip install pyautogui
pyautogui works both for python 2 and 3.