Python Programming Workshop-Super Introductory Vol.3

Before the main subject


Positioning / premise

This article was prepared for the ** In-house Workshop **. Therefore, please understand that we will proceed on the following assumptions.


Purpose of this workshop

The purpose is to allow participants to ** stand at the entrance where they can self-study as needed **.


How to proceed with the workshop

The workshop basically focuses on hands-on. (Some explanations are included)


Caution

This workshop is expected to be ** 60-120 minutes **. Therefore, we do not do ** systematic learning ** because we do not have enough time for full-scale learning.

In order to be able to create the program you want from scratch in earnest, you need to study by yourself or take some kind of course.


target

This workshop is mainly aimed at the following participants.

Please note that there are many things that I do not dare to mention because I do not deal with intermediate and advanced people at all.


Preparing the programming environment

Please see here.


Last review

Please answer the following questions.

review3-1.py


for i in range(5):
    print("Yes")

review3-3.py


a = (3 * 5 + 1 ) / 2
print(a)

What I remembered last time


Today's goal

Create a script (almost Slack bot) that posts to Slack on a regular and random basis.

If possible, make sure you understand what you wrote later. However, you don't have to remember it perfectly.


Hands-on start


Hands-on 1


Hands-on 1-0. Preparing your Slack account and upload destination

As before, prepare the following.

The last Slack upload destination URL will be referred to as "** POST destination URL **" from now on. (The reason was last time)


Hands-on 1-1. Post to Slack (same as last time)

Save the following script as exp311.py in the c: \ script folder and run it.

ex311.py


import requests
import json

URL = "[POST destination URL]"
MESSAGE = json.dumps({"text": "TEST"})
requests.post(URL, MESSAGE)

Of course, replace [POST destination URL] with the prepared URL.


Hands-on 1-2. Post to Slack in 10 seconds

Copy ex11.py and rewrite it as follows. (You can copy the code you wrote)

ex312.py


import requests
import json
import time

time.sleep(10)
URL = "[POST destination URL]"
MESSAGE = json.dumps({"text": "TEST"})
requests.post(URL, MESSAGE)

Then save exp312.py and run the script.


Hands-on 1-3. Post the current date and time to Slack

Copy ex11.py and rewrite it as follows. (You can copy the code you wrote)

ex313.py


import requests
import json
import datetime

NOW = datetime.datetime.now()
URL = "[POST destination URL]"
MESSAGE = json.dumps({"text": str(NOW)})
requests.post(URL, MESSAGE)

Then save exp313.py and run the script.


Commentary 1


Programming crap (review)


Hands-on 1-2 commentary

Here is the difference between the executed ex312.py and ex311.py.

ex312.py (excerpt)


import time

I'm importing a time module that handles time here.

ex312.py (excerpt)


time.sleep(10)

With this command, I try to sleep for 10 seconds.

Nothing is displayed while waiting for 10 seconds, but when you count it, it is a mechanism to wait for 10 seconds before posting.

If you want to make it sleep like this, use the following.

sleep format


time.sleep(The number of seconds)

This is one of the most frequently used processes, such as waiting for a few seconds to a few days.


Hands-on 1-3 Commentary

Here is the difference between the executed ex313.py and ex311.py.

ex312.py (excerpt)


import datetime

Import the datetime module that handles time here.

The time module mentioned earlier is a module that focuses on tools that deal with time, but the datetime module is a module that mainly performs various operations on the date and the time itself.

ex312.py (excerpt)


NOW = datetime.datetime.now()

This instruction stores the current time in the variable NOW.

ex312.py (excerpt)


MESSAGE = json.dumps({"text": str(NOW)})

This str (NOW) is the point.

NOW stores time data and can be recognized by the human eye as text (character string) that represents the time.

However, computers have the characteristic that character strings and time data cannot be treated as data together.

The characteristics of data in this way are called ** data type (type) **.

The time data stored in NOW is ** time type **, and the character string (text) type is ** string (String) **.

There are many ** data types (types) **, but for the time being, just put ** time type ** and ** string type (string / String) ** in the corner of your head.

ex312.py (excerpt)


MESSAGE = json.dumps({"text": str(NOW)})

In this description, I am creating a Slack post message, but the point is ** str (NOW) **.

Normally, NOW should be fine, but if it is left as it is, an error will occur.

This is because ** NOW is not a string type **.

As a promise, all JSON formats must be strings.

Therefore, by using str (NOW), the value stored in NOW can be converted to a character string type.

It's a very annoying "type", but this mechanism also has the effect of preventing incorrect data from being mixed in.

Therefore, let's get used to it gradually.


Hands-on 2


Hands-on 2-1. Post to Slack at random times

Save the following script as exp321.py in the c: \ script folder and run it.

ex321.py


import requests
import json
import random
import time

URL = "[POST destination URL]"
MESSAGE = json.dumps({"text": "TEST"})
num = random.randint(1, 10)
time.sleep(num)
requests.post(URL, MESSAGE)

Of course, replace [POST destination URL] with the prepared URL.


Hands-on 2-2. Turn on the switch to post to Slack

Save the following script as exp322.py in the c: \ script folder and run it.

ex322.py


import requests
import json

flag = True
URL = "[POST destination URL]"
MESSAGE = json.dumps({"text": "TEST"})
if flag is True:
    requests.post(URL, MESSAGE)

Of course, replace [POST destination URL] with the prepared URL.


Hands-on 2-3. Post to Slack if "OK" is included

Save the following script as exp23.py in the c: \ script folder and run it.

ex323.py


import requests
import json

URL = "[POST destination URL]"
MESSAGE = json.dumps({"text": "TEST"})
if "OK" in MESSAGE:
    requests.post(URL, MESSAGE)

MESSAGE = json.dumps({"text": "It is OK."})
if "OK" in MESSAGE:
    requests.post(URL, MESSAGE)

Of course, replace [POST destination URL] with the prepared URL.


Commentary 2


Hands-on 2-1 Commentary

Here is the point to check in the executed ex321.py.

ex321.py (excerpt)


import random

Here we load the module to generate a random number.

ex321.py (excerpt)


num = random.randint(1, 10)

It is a process that generates a random number.

There are several types that represent numbers, but Python often deals with the following two.

These are the same numbers, but you need to keep in mind that they may be used differently.

Based on this, ** randint ** is used as an instruction to generate "random number = random integer".

By the way, in order to generate only one integer from 1 to 10 at random, I wrote a command as random.randint (1, 10).

random.randint format


random.randint(Number of starts,Number of ends)

Please understand that the formula is the number of starts <= N <= the number of ends.


Hands-on 2-2 Commentary

Here is the point to check in the executed ex322.py.

ex322.py (excerpt)


flag = True

I put a value in a variable that is neither a string nor a number.

The value expressed by True / False here is called ** Boolean **.

A simple data type used when dealing only with truth.

ex322.py (excerpt)


if flag is True:
    requests.post(URL, MESSAGE)

Here, it is a statement indicating the "condition" to be executed.

If the value of the variable flag is True, the indented content below is executed.

The command that expresses this "condition" is called an "if statement" and is used very often.

IF document formula


if {conditions}:
Execution content

There can be multiple execution contents. All indented parts are considered the same.

IF statement example


if a == 1:
    b == 1
    print(b)
    print(a)
    print("If b is 1, it will be executed so far")

It is an IF statement that always appears as the basis of programming.

It's simple, but there are many opportunities to use it, so let's remember it.


Hands-on 2-3 commentary

Here are the points to check in the executed ex323.py.

ex323.py (excerpt)


MESSAGE = json.dumps({"text": "TEST"})
if "OK" in MESSAGE:
    requests.post(URL, MESSAGE)

The "if" OK "in MESSAGE:" specified in the IF statement means "if the variable MESSAGE contains the character string" OK "".

In this way, use ** in ** to determine whether a variable contains the specified string.

in format


if {The string you want to be included} in {Character string to be confirmed}:

In the same way, the IF statement determines the variable MESSAGE whose content of the character string to be confirmed has been changed.

ex323.py (excerpt)


MESSAGE = json.dumps({"text": "It is OK."})
if "OK" in MESSAGE:
    requests.post(URL, MESSAGE)

In this case, the point is that it does not match exactly, and the criterion is that it should be included in the character string (text) of the variable MESSAGE.

As you can see, there are various conditions (called conditional expressions) in IF statements.


Hands-on 3


Hands-on 3-1. Post to Slack after 10am

Save the following script as exp331.py in the c: \ script folder and run it.

ex331.py


import requests
import json
import datetime

NOW = datetime.datetime.now()
AM10 = NOW.replace(hour=10, minute=0, second=0, microsecond=0)

URL = "https://hooks.slack.com/services/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"
MESSAGE = json.dumps({"text": "It's past 10 o'clock."})

print("Currently" + str(NOW) + "is.")
print(str(AM10) + "I will post it after that.")

if AM10 <= NOW:
    requests.post(URL, MESSAGE)
    print("I posted it on Slack.")

Of course, replace [POST destination URL] with the prepared URL.


Hands-on 3-2. Post to Slack from 10am to 6pm

Save the following script as exp332.py in the c: \ script folder and run it.

ex332.py


import requests
import json
import datetime

NOW = datetime.datetime.now()
AM10 = NOW.replace(hour=10, minute=0, second=0, microsecond=0)
PM18 = NOW.replace(hour=18, minute=0, second=0, microsecond=0)

URL = "https://hooks.slack.com/services/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"
MESSAGE = json.dumps({"text": "It's past 10 o'clock."})

print("Currently" + str(NOW) + "is.")
print(str(AM10) + "~" + str(PM18) + "I will post it.")

if AM10 <= NOW <= PM18:
    requests.post(URL, MESSAGE)
    print("I posted it on Slack.")

Of course, replace [POST destination URL] with the prepared URL.


Commentary 3


Hands-on 3-1 commentary

Here is what you should check in the executed ex331.py.

ex331.py


NOW = datetime.datetime.now()

You are putting the current time in the variable NOW.

This command datetime.datetime.now () is long, but it's standard, so use it as needed. (If you understand, copying is enough.)

ex331.py


AM10 = NOW.replace(hour=10, minute=0, second=0, microsecond=0)

It is an instruction that puts the time data indicating "10 am" in the variable AM10.

This contains the time data of the variable NOW with the time replaced at 10 o'clock.

It may seem strange, but think of it as one of the ways to handle data based on the present.

ex331.py


print("Currently" + str(NOW) + "is.")
print(str(AM10) + "I will post it after that.")

The variable NOW introduced earlier is converted to a string.

In addition, connect the strings with a + to join them together.

By doing so, you can display a combination of strings and variables.

ex331.py


if AM10 <= NOW:
    requests.post(URL, MESSAGE)
    print("I posted it on Slack.")

The variable NOW that represents the present is larger than the variable AM10 created earlier, that is, the IF statement says "if it is past 10 am".

The conditions themselves are not complicated, but can you understand that it takes some effort to prepare the data for use in the conditions?

In programming, there are a lot of tasks such as preparing things to compare and matching the molds.


Hands-on 3-2 Commentary

This is the culmination of the contents explained so far.

Here are the points to check in ex332.py.

ex332.py (excerpt)


AM10 = NOW.replace(hour=10, minute=0, second=0, microsecond=0)
PM18 = NOW.replace(hour=18, minute=0, second=0, microsecond=0)

Here, the variable AM10 contains the time data indicating "10 am", and the variable PM18 contains the time data indicating "18:00".

ex332.py (excerpt)


if AM10 <= NOW <= PM18:
    requests.post(URL, MESSAGE)
    print("I posted it on Slack.")

The IF statement indicates the condition "after 10 am until 6 pm".

In this way, it is one of the features of Python that you can set multiple conditions at once.

Even if you write as follows, it will work the same.

ex332.py (excerpt)


if AM10 <= NOW and NOW <= PM18:
(abridgement)

If it is easier to read if omitted, use positively easy-to-read notation.


Exercises

Let's create a script that meets these requirements and run it.

** Q. A script that posts "Good morning" to Slack at 7am every morning **

The points to consider are as follows.


At the end

This time as well, I tried to make a workshop packed with the basic essence of programming.

In particular, we introduced "conditional expressions," "text formatting," and "comparison operations" as important keywords in programming.

The basic structure should have been covered to some extent this time.

Next time, I would like to deepen my understanding by reviewing the basics I have learned so far and creating a slightly different program.

In addition, although there are many parts where the explanation is broken, please be patient as it is for beginners.

If you would like to continue learning, please make a request.


official


Python reference site


Python related books


Python learning service

A collection of easy-to-use web services / online schools.

Recommended Posts

Python Programming Workshop-Super Introductory Vol.3
Python Programming Workshop-Super Introductory Vol.4
Python Programming Workshop-Super Introductory Python Execution Environment
Python programming note
Programming in python
3. 3. AI programming with Python
Competitive programming diary python 20201213
Python programming with Atom
Competitive programming diary python 20201220
Competitive programming with python
Python programming in Excel
LEGO Mindstorms 51515 Python Programming
[Python] Dynamic programming ABC015D
Competitive programming diary python
Programming with Python Flask
Programming with Python and Tkinter
Python3 programming functions personal summary
Atcoder Acing Programming Contest Python
[Python] Dynamic programming knapsack problem
[Python] Dynamic programming TDPC D
Python web programming article summary
Paiza Python Primer 1 Learn Programming
Python Competitive Programming Site Summary
Python Machine Learning Programming> Keywords
An introduction to Python Programming
[Python] Dynamic programming TDPC A
Network programming with Python Scapy
[Swift / Ruby / Python / Java] Object-oriented programming
Python3 standard input for competitive programming
GUI programming in Python using Appjar
Functional programming in Python Project Euler 1
[Introduction to Python3 Day 1] Programming and Python
Competitive programming, coding test template: Python3
Functional programming in Python Project Euler 3
[Python] [Table of Contents Links] Python Programming
[Python] Object-oriented programming learned with Pokemon
"The easiest Python introductory class" modified
Introductory Python Modules and conditional expressions
Easy Python + OpenCV programming with Canopy
Functional programming in Python Project Euler 2
python documentation reading socket programming HOWTO
Introductory table of contents for python3