[JAWS-UG CLI] Lambda Blueprint Explanation: Python2.7 Basics

Lambda's Python beginner's commentary.

--Lambda Blueprint Explanation: Lambda Common Edition (Python): http://qiita.com/tcsh/items/e119d7fd8257e15e599b

--Lambda: # 16 sns-message (Python version): http://qiita.com/tcsh/items/c776221b000e5f921fcc --Lambda: # 15 canary (Python version): http://qiita.com/tcsh/items/15815f61df418fbe6be7

Basics

comment

The end of the line is ignored as a comment from \ #.

python:code(Line comment):


   word = 'hello'   #Target word

When commenting out multiple lines, insert the comment part with three single quotes or double quotes at the same position as the indent of the previous line. (Because it is treated as a character string, it is not executed.)

python:code(De facto multi-line comment):


   def validate(res):
     '''[from here] Return False to trigger the canary

     Currently this simply checks whether the EXPECTED string is present.
     However, you could modify this to perform any number of arbitrary
     checks on the contents of SITE.
     [So far]'''
     return EXPECTED in res

Variable (constant)

Python does not support constants.

It is customary to write constants in uppercase.

python:code(Example):


   SITE = 'https://www.amazon.com/'  # URL of the site to check
   EXPECTED = 'Online Shopping'  # String expected to be on the page

If declared outside the function, the scope is the entire module (file).

in operator

Find out if a value exists.

python:code(Example of use in the return value of a function):


   return EXPECTED in res

Check if the character string defined by the constant EXPECTED exists in the res object.

module

Import method

from: Specify the package or module name.

import: Specify the package or module name, class or function name, variable name, etc.

python:Import a datetime function object from the datetime module:


from datetime import datetime

python:urllib2 module(For Python 2)Import the urlopen function object from:


from urllib2 import urlopen

Note: The urllib module has been split into urllib.request, urllib.parse, urllib.parse in Python3.

future module

Allows Python2 to use features that are implemented in Python3 and are incompatible with Python2.

python:code(Example):


from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals

from future_builtins import *

Note: from future import * cannot be defined.

future module (print_function)

In Python2 it was a print statement, but in Python3 it became a function print ().

By writing the following, you can use print () compatible with Python3.

python:code(Example):


from __future__ import print_function

function

print()

In Python3, print () prints the contents of the string object.

python:code(Example):


   print('hoge')
   print('hoge' + variable_a)
   print('a: [', variable_a, ']')

python:code(Example of end specification of print):


   print('hoge', end='')

python:code(File output example):


   f = open('test.txt', 'w')
   print('hoge', file=f)

datetime.now()

Methods contained in the datetime object. Provides the ability to return the current local date and time.

python:code(Example):


datetime.now()

python:result(Example):


   datetime.datetime(2016, 5, 29, 18, 52, 57, 727727)

Note: Year, month, day, hour, minute, second, microsecond

str()

Returns a string that represents the object in a printable form.

python:code(Example):


   print(str(datetime.now()))

python:result(Example):


   2016-05-29 18:52:57.727714

urlopen()

Objects included in the urllib2 module. Provides the ability to retrieve content on the Web.

Since the obtained response is a file-like object, it can be read by read ().

python:code(Example):


   if not validate(urlopen(SITE).read()):

User-defined function

Users can define their own functions.

python:syntax:


def function name(argument):
Description

return Return value

If there is no return statement, it returns'None'.

python:code(Example):


   def validate(res):
     # (snip)
     return EXPECTED in res

--Arguments: res --Return value: Bool value (whether there is an EXPECTED string in res)

python:code(Example):


   def lambda_handler(event, context):
     # (snip)

--Arguments: event and context --Return value: None

Control syntax

if statement

It can be branched depending on the conditions.

python:syntax:


   if (conditions):
Description

   elif (conditions):
Description

   else:
Description

python:sample:


   if not validate(urlopen(SITE).read()):
       raise Exception('Validation failed')

Exception related

try statement

You can get an exception and handle it as it occurs.

python:syntax:


   try:
Description that can cause an exception

   except:
Description when an exception occurs(Multiple descriptions can be made for each exception type)

Built-in exception: http://docs.python.jp/2/library/exceptions.html

   else:
Description when no exception occurs

   finally:
A description of the action that is always executed before exiting the try statement, regardless of whether an exception has occurred.

python:sample:


   def lambda_handler(event, context):
     print('Checking {} at {}...'.format(SITE, event['time']))
     try:
         if not validate(urlopen(SITE).read()):
             raise Exception('Validation failed')

     except:
         print('Check failed!')
         raise

     else:
         print('Check passed!')
         return event['time']

     finally:
         print('Check complete at {}'.format(str(datetime.now())))

Part of try and except statements

(See Exception class and raise statement below)

part of the else statement

python:code(Example):


   else:
       print('Check passed!')
       return event['time']

If validate () is not False, execute the print statement and return the time key value of the event data.

Finally statement part

python:code(Example):


   finally:
         print('Check complete at {}'.format(str(datetime.now())))

'Check complete at current time' is output to standard output.

python:result(Example):


   Check complete at 2016-05-29 18:00:15.508132

Module: Exception class

One of the exception classes included in the exception module. The exception module does not need to be imported.

Built-in exceptions: http://docs.python.jp/2/library/exceptions.html

code


raise Exception('Validation failed')

Of all the built-in exceptions, those that are not system-terminated are derived from this class. All user-defined exceptions should be derived classes of this class.

Statement: raise

It is used when you want to intentionally raise an exception.

When used alone, it immediately throws an exception.

When using it in a try .. exception statement, define the exception to be thrown by raise in the try statement and describe'raise' in the except clause to actually return the exception.

python:code(Example):


   try:
       if not validate(urlopen(SITE).read()):
           raise Exception('Validation failed')

If validate () is not True, define an exception (throw an Exception class'Validation failed').

python:code(Example):


   except:
       print('Check failed!')
       raise

When an exception occurs, execute the print statement and raise the exception defined in the try statement.

Method

String object .format ()

Provides the ability to perform complex variable substitutions and value formatting for string objects.

python:code(Example):


   print('Checking {} at {}...'.format(SITE, event['time']))

python:result(Example):


   'Checking site URL at time...'

File object .read ()

Methods contained in the file object. Provides a function to read the file contents.

python:code(Example):


   if not validate(urlopen(SITE).read()):

Recommended Posts

[JAWS-UG CLI] Lambda Blueprint Explanation: Python2.7 Basics
[JAWS-UG CLI] Lambda Blueprint Explanation: Lambda Common Edition (Python)
Python basics ⑤
Python basics
Python basics ④
Python basics ③
Python basics
Python basics
Python basics
Python basics ③
Python basics ②
Python basics ②
Python basics memorandum
#Python basics (#matplotlib)
Python CGI basics
Python basics: dictionary
Basics of Python ①
Basics of python ①
Python slice basics
#Python basics (scope)
#Python basics (#Numpy 1/2)
#Python basics (#Numpy 2/2)
#Python basics (functions)
Python array basics
Python profiling basics
Python #Numpy basics
Python basics: functions
#Python basics (class)
Python basics summary
Python basics ② for statement
Python: Unsupervised Learning: Basics
A python lambda expression ...
Basics of Python scraping basics
Python basics 8 numpy test
Errbot: Python chatbot basics
#Python DeepLearning Basics (Mathematics 1/4)
Python basics: Socket, Dnspython
# 4 [python] Basics of functions
Basics of python: Output