[Python tutorial] Control structure tool

Introduction

This is an attempt to read the 3rd edition of the Python tutorial and make a note of what you have learned.

Python Tutorial 3rd Edition

And when I finish reading, I would like to take this exam By the end, the test has started ...!

** Let's get started! ** **

Python 3 Engineer Certification Basic Exam

I hope it continues, I hope it continues

Control structure tool

if statement

>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...     x = 0
...     print('Negative number is zero')
... elif x == 0:
...     print('zero')
... elif x == 1:
...     print('One')
... else:
...     print('More')
...
More

for statement

--Repeat items in any sequence (list or string) in the order within that sequence

>>> #Measure the length of a string:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
...     print(w, len(w))
...
cat 3
window 6
defenestrate 12

--If you need to modify the sequence you are repeating, it is recommended to make a copy and repeat it. --No implicit copying is made by repeating the sequence

>>> for w in words[:]: #Loop through slice copy of the entire list
...     if len(w) > 6:
...         words.insert(0, w)
...
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']

range () function

--The built-in function range () is useful when iterating over a series of numbers. --Generate arithmetic progression

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4

--The given termination value is not included --The value of 10 generated by range (10) is just an index for each item in a sequence of length 10 --range () can start with a number other than 0 --Increment (step) can also be specified

range(5, 10)
→ From 5 to 9
range(0, 10, 3)
→ 0, 3, 6, 9
range(-10, -100, -30)
→ -10, -40, -70

--If you want to iterate at the index of the sequence, you can combine range () and len () as follows: --In such cases, it is convenient to use the ʻenumerate ()` function.

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
...     print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb

--The object returned by the range () function behaves like a list in many ways, but not a list. --An object that continuously returns items in the desired sequence by iterating, thereby saving space. --Such an object is called ** iterable ** ――This means something that supplies items continuously until it becomes, and something that is suitable as a target for functions and structures that expect such things. --Functions and structures that expect repeatable bodies are called ** iterators **. --The list () function, which creates a list from an iterator, is also an iterator.

>>> list(range(5))
[0, 1, 2, 3, 4]

break statement and continue statement, else clause in loop

--The break statement breaks the for or while loop --A ʻelse clause is added to these loop statements --ʻElse clause is executed when the loop ends due to the list being exhausted or the conditional expression becomes false, and not executed when it ends with the break statement.

>>> for n in range(2, 10):
...     for x in range(2, n):
...         if n % x == 0:
...             print(n, 'equals', x, '*', n//x)
...             break
...     else:
...         #If you can't find a divisor in the loop
...         print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

--The continue statement skips the rest of the loop and goes to the next iteration

>>> for num in range(2, 10):
...     if num % 2 == 0:
...         print("Found an even number", num)
...         continue
...     print("Found a number", num)
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9

pass statement

Use when you don't need to do anything programmatically

>>> while True:
...     pass #Keyboard interrupt with busy waiting(Ctrl+C)Wait for
...

Often used to generate the smallest class

>>> class MyEmptyClass:
...     pass
...

Another use for the pass statement is to put it as a placeholder in the body of a function or condition when writing new code to help you think about the abstract level.

>>> def initlog(*args):
...     pass #Don't forget to implement!
...

Function definition

--The keyword def is the beginning of the function definition, followed by the function name and the parenthesized parameter list. --Write the function body statement indented from the next line

A function that writes the Fibonacci series up to an arbitrary upper limit


>>> def fib(n): #Export Fibonacci series to n
...     """Display Fibonacci series up to n"""
...     a, b = 0, 1
...     while a < n:
...     print(a, end=' ')
...     a, b = b, a+b
...     print()
...
>>> #Let's call this function
... fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

Further about function definition

--It is also possible to define a function with a variable number of arguments ――There are three forms, and it is possible to combine them.

Default value of argument

――The most used form --The following functions can be called in various ways --Give only required arguments - ask_ok('Do you really want to quit?') --Give one optional argument - ask_ok('OK to overwrite the file?', 2) --Give all arguments - ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')

def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
    while True:
        ok = input(prompt)
        if ok in ('y', 'ye', 'yes'):
            return True
        if ok in ('n', 'no', 'nop', 'nope'):
            return False
        retries = retries - 1
        if retries < 0:
            raise OSError('Non-cooperative user')
        print(complaint)

** Default value evaluation only happens once. ** ** This has an effect if the default values are variable objects: lists, dictionaries, and instances of most classes.

For example, the following function accumulates the arguments passed in the call

>>> def f(a, L=[]):
...     L.append(a)
...     return L
...
>>> print(f(1))
[1]
>>> print(f(2))
[1, 2]
>>> print(f(3))
[1, 2, 3]
>>>

If you don't want the default values to be shared between calls, you can write this function like this:

>>> def f(a, L=None):
...     if L is None:
...             L = []
...     L.append(a)
...     return L
...
>>> print(f(1))
[1]
>>> print(f(2))
[2]
>>> print(f(3))
[3]

Keyword arguments

--Functions can also take ** keyword arguments ** in the form "keyword = value"

>>> def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
...     print("-- This parrot wouldn't", action, end=' ')
...     print("if you put", voltage, "volts through it.")
...     print("-- It's", state, "!")
...

This function takes one required argument (voltage), three optional arguments (state, action, type), and can be called in any of the following forms:

>>> #One positional argument
>>> parrot(1000)
-- This parrot wouldn't voom if you put 1000 volts through it.
-- It's a stiff !
>>> #One keyword argument
>>> parrot(voltage=1000)
-- This parrot wouldn't voom if you put 1000 volts through it.
-- It's a stiff !
>>> #Two keyword arguments
>>> parrot(voltage=1000000, action='VOOOOOM')
-- This parrot wouldn't VOOOOOM if you put 1000000 volts through it.
-- It's a stiff !
>>> #Three keyword arguments
>>> parrot(action='VOOOOOM', voltage=1000000)
-- This parrot wouldn't VOOOOOM if you put 1000000 volts through it.
-- It's a stiff !
>>> #3 positional arguments
>>> parrot('a million', 'bereft of life', 'jump')
-- This parrot wouldn't jump if you put a million volts through it.
-- It's bereft of life !
>>> #One positional argument, one keyword argument
>>> parrot('a thousand', state='pushing up the daisies')
-- This parrot wouldn't voom if you put a thousand volts through it.
-- It's pushing up the daisies !

But the following call is invalid

>>> #Missing required arguments
>>> parrot()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: parrot() missing 1 required positional argument: 'voltage'
>>> #Non-keyword arguments after keyword arguments
>>> parrot(voltage=5.0, 'dead')
  File "<stdin>", line 1
SyntaxError: positional argument follows keyword argument
>>> #Given the same argument twice
>>> parrot(110, voltage=220)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: parrot() got multiple values for argument 'voltage'
>>> #Unknown keyword argument
>>> parrot(actor='John Cleese')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: parrot() got an unexpected keyword argument 'actor'

Whenever you call a function, ** positional arguments must come first and keyword arguments come after **

All keyword arguments must match what is written in the formal argument of the function definition (the argument actor is invalid in the parrot function), but the order does not matter.

This is also true for non-optional arguments (eg parrot (voltage = 1000) is also valid)

The argument can only take a value once. The following is an example of failure due to this limitation. A type error has occurred because the keyword argument "a" of function () has multiple values.

>>> def function(a):
...     pass
...
>>> function(0, a=0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: function() got multiple values for argument 'a'

If the formal argument ends in the form of a ** name, this argument receives a dictionary. This dictionary contains all keyword arguments except the keywords that correspond to the formal arguments. In other words, in this form, keywords that are not in the formal parameters can be used.

It can also be used in combination with the * name format. (The * name must precede the ** name.)

In this format, a tuple containing all positional arguments that are not in the formal arguments is passed to the function. Therefore, if you define the following function

>>> def cheeseshop(kind, *arguments, **keywords):
...     print("-- Do you have any", kind, "?")
...     print("-- I'm sorry, we're all out of", kind)
...     for arg in arguments:
...             print(arg)
...     print("-" * 40)
...     keys = sorted(keywords.keys())
...     for kw in keys:
...             print(kw, ":", keywords[kw])
...

You can call it like this and the output will be:

>>> cheeseshop("Limburger", "It's very runny, sir.", "It's really very, VERY runny, sir.", shopkeeper="Michael Palin", client="John Cleese", sketch="Cheese Shop Sketch")
-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch

Note that when displaying the contents of the keywords dictionary, we first sort the results of thekey ()method and generate a list of keyword arguments. If this is not done, the display order of the arguments will be undefined.

List of optional arguments

--A method of writing a function so that it can be called with an arbitrary number of arguments --Not often used --The arguments from this are grouped into tuples. --A normal argument can be placed before this variable number of arguments.

>>> def write_multiple_items(file, separator, *args):
...     file.write(separator.join(args))

Variadic arguments are placed at the end of the formal argument list. This is because it sucks in all the rest of the arguments passed to the function. In the case of * args format, all formal arguments after this are "keyword only" arguments. In other words, it can only be used as a keyword argument, not a positional argument.

>>> def concat(*args, sep="/"):
...     return sep.join(args)
...
>>> concat("earth", "mars", "venus")
'earth/mars/venus'
>>> concat("earth", "mars", "venus", sep=".")
'earth.mars.venus'

Unpacking the argument list

The opposite situation is that what you want to be an argument is already a list or tuple and you have to unpack it for a function that requires a positioned argument.

For example, the built-in range () function expects separate arguments for start and stop.

If you don't have them individually, you can pass unpacked arguments from a list or tuple by calling the function with the * operator.

>>> #Ordinary call with individual arguments
>>> list(range(3, 6))
[3, 4, 5]
>>> args = [3, 6]
>>> #Call with unpacked arguments from list
>>> list(range(*args))
[3, 4, 5]

Similarly, you can use the ** operator to pass a dictionary as a keyword argument.

>>> def parrot(voltage, state='a stiff', action='voom'):
...     print("-- This parrot wouldn't", action, end=' ')
...     print("if you put", voltage, "volts through it.", end=' ')
...     print("E's", state, "!")
...
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !

lambda expression

--Use the keyword lambda to multiply a small anonymous function --lambda a, b: a + b is a function that returns the sum of two arguments --Lambda functions can be used wherever a function object is needed --However, this format has a syntactic limitation that only a single expression is popular. --Semanticsally, this form is just syntactic sugar on an ordinary function definition. --Like nested function definitions, lambda functions can also reference variables in the scope that surrounds them.

>>> def make_incrementor(n):
...     return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43

The above is an example of returning a function using a lambda expression. Another use is when passing a small function as an argument

>>> pairs = [(1, 'one'), (2, 'tow'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'tow')]

Documentation string (docstring)

--The first line should always be a short and concise summary of the object's purpose --I don't specify what else you can get, such as the name or type of the object.
(except if the function name is already a verb that describes its behavior). --This line starts with a capital letter and ends with a period --If there is a continuation, leave the second line of the documentation string blank to visually separate the summary from other descriptions. --In the following lines, use paragraphs to describe ** how to call ** and ** side effects ** of the object. --The Python parser does not remove the indentation of multi-line string literals, so if you want to remove it, you need to do it in the document processing tool. ――First, the non-blank line after the first line is used as the standard for indentation of the entire documentation string.
(The first line cannot be used. This is generally immediately after the quotation mark. , The amount of indentation is not reflected in the string literal body) --Remove the "equivalent" white space from this indentation amount from the beginning of each work in the string.

Below is an example of a multi-line docstring (note the part called by __doc__)

>>> def my_function():
...     """Do nothing, but document it.
...
...     No, really, it doesn't do anything.
...     """
...     pass
...
>>> print(my_function.__doc__)
Do nothing, but document it.

        No, really, it doesn't do anything.

Function annotation (function annotation)

--Function annotations are human options --Type metadata information used in user-defined functions --Annotations are stored as dictionaries in the function's __annotations__ attribute. --Does not affect any other part of the function --The argument annotation can be defined by following the argument name with a colon and an expression, and this expression is evaluated and becomes the value of the annotation. --The return value annotation is defined by inserting a literal "->" and an expression between the formal argument list and before the last colon for def minutes.

>>> def f(ham: str, eggs: str = 'eggs') -> str:
...     print("Annotations:", f.__annotations__)
...     print("Arguments:", ham, eggs)
...     return ham + ' and ' + eggs
...
>>> f('spam')
Annotations: {'ham': <class 'str'>, 'eggs': <class 'str'>, 'return': <class 'str'>}
Arguments: spam eggs
'spam and eggs'

Coding style (only the main points from PEP8)

--Indent with 4 spaces, no tabs --Wrap lines with 79 characters or less --Use blank lines to separate functions, classes, and even larger blocks within functions --Comment lines should be independent if possible --Use docstring --Put a space around the operator or after the comma, but not just inside the parentheses

the term

sequence

--A sequence type is a collection of ordered elements such as a character string or a list. --There are 6 sequence types in the built-in type. --String --Unicode string --List --Tuple --Buffer --xrange object

Iterable

――The structure that can be iterated is called iterable. ――Iteration is "repeating" and "accessing the next element" --As an example, an object that can be turned with a for statement --Strictly speaking, an object that can be an iterator

Iterator

--Iterable object that remembers the state (iteration location) ――Iterator is one of the iterable objects --You can create an iterator from an iterable object using the iter function. --The iterator can advance the state by the next method, and raises an exception called StopIteration when the iterator becomes impossible (in this case, the last element is reached). --The next function is not the only one that can advance the iterator

Placeholder

--Measures to temporarily secure a place until the official value is entered

Unpack

When the right side is a tuple, you can expand the contents by placing multiple variables on the left side. This is called sequence unpack, but I don't quite understand the usage and meaning of the word "unpack" ... \ (^ o ^) /

Arithmetic progression

I'm not sure ... \ (^ o ^) /

Reference information

Recommended Posts

[Python tutorial] Control structure tool
[Python tutorial] Data structure
Python tutorial
Python Django Tutorial (5)
Python Django Tutorial (2)
Python tutorial summary
Python Django Tutorial (8)
Python Django Tutorial (6)
Install Python Control
Python internal structure
Python Django Tutorial (7)
Python Django Tutorial (1)
Python Django tutorial tutorial
Python Django Tutorial (3)
Python Django Tutorial (4)
[Docker] Tutorial (Python + php)
Python Django tutorial summary
C-like structure in Python
Python control syntax (memories)
Python OpenCV tutorial memo
Cloud Run tutorial (python)
First Fabric (Python deployment tool)
data structure python push pop
[Python] Decision Tree Personal Tutorial
Instrument control using Python [pyvisa]
[ev3dev × Python] Single motor control
AI Edge Contest (Implementation Contest) Tutorial [10: Control HW with Python ..., but ...]
week4: Control structure / eval function
Python Django Tutorial Cheat Sheet
Python control syntax, functions (Python learning memo ②)
EEG analysis in Python: Python MNE tutorial
Virtual Environment Version Control Summary Python
[ev3dev × Python] Control of multiple motors
3D skeleton structure analysis with Python
Study from Python Hour2: Control statements
Python package management tool personal summary
Created AtCoder test tool for Python
[Python] Creating a scraping tool Memo
[ev3dev × Python] Display, audio, LED control
Picture book data structure algorithm Python
Try frequency control simulation with Python
[Python Tutorial] An Easy Introduction to Python
Tips (control structure) that you should know when programming competitive programming with Python2