Python control syntax, functions (Python learning memo ②)

This time is a learning memo about control syntax and functions.

if statement

point

#You can wait for input like this
x = int(input("Please enter an integer: "))

if x < 0:
    x = 0
    print ("Negative number is zero")
elif x == 0:
    print("zero")
elif x == 1:
    print("One")
else:
    print("More")

for statement

point


#Measure the length of a string
words = ['cat', 'window', 'defenstrate']
for w in words:
    print(w, len(w))

#output
# cat 3
# window 6
# defenstrate 11

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

#output
# ['defenstrate', 'cat', 'window', 'defenstrate']

range () function

point


#Iteration by range
for i in range(5):
    print(i)

#output
# 0
# 1
# 2
# 3
# 4

#Iteration using sequence index
a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
    print(i, a[i])

#output
# 0 Mary
# 1 had
# 2 a
# 3 little
# 4 lamb

break statement and continue statement, else clause in loop

point


for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print(n, 'equals', x, '*', n//x)
            break
    else:
        #This else depends on for
        #If you can't find a divisor in the loop
        print(n, 'is a prime number')

#output
# 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

pass statement

point

while True:
    pass #Do nothing Ctrl+Wait to finish with C

#Generate the smallest class
class MyEmptyClass
    pass

#Function definition
def initLog(*args):
    pass #Erase after implementation


Function definition

point

def fib(n):
    """Display Fibonacci series up to n"""
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a+b
    print()

fib(2000)

#output
# 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

Further about function definition

Default value of argument

point

#Example ①
i = 5

def f(arg=i):
    print(arg)

i = 6
f()

#output
# 5

#Example ②
def f(a, L=[]):
    L.append(a)
    return L

print(f(1))
print(f(2))
print(f(3))

#output
# [1]
# [1, 2]
# [1, 2, 3]

Keyword arguments

point

def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
    print("-- This parrot wouldn't", action, end=' ');

#You can call in any of the following ways
parrot(1000)                                         #1 positional argument
parrot(voltage=1000)                                 #1 keyword argument
parrot(voltage=100000000, action='VOOOOOM')          #2 keyword arguments
parrot(action='VOOOOOOOM', voltage=1000000)          #2 keyword arguments
parrot('a million', 'bereft of life', 'jump')        #3 positional arguments
parrot('a tousand', state='pushing up the daisies')  #1 positional argument 1 keyword argument

#Next call is invalid
# parrot()                     #Missing required arguments
# parrot(voltage=5.0, 'dead')  #Non-keyword arguments after keyword arguments
# parrot(110, voltage=220)     #Given the same argument twice
# parrot(actor='John Cleese')  #Unknown keyword argument
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])
            
cheeseshop("Limburger", "It's very runny, sir.",
           "It's really very, VERY runny, sir.",
           shopkeeper="Michael Palin",
           client="John Cleese",
           sketch="Cheese Shop Sketch")

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

List of optional arguments

point

def concat(*args, sep="/"):
    return sep.join(args)

print(concat("earth", "mars", "venus"))

#output
# earth/mars/venus

print(concat("earth", "mars", "venus", sep="."))

#output
# earth.mars.venus

Unpacking the argument list

point

>>> list(range(3, 6))
[3, 4, 5]

>>> args = [3, 6]
>>> list(range(*args))
[3, 4, 5]
>>> 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

point

def make_incrementor(n):
    return lambda x: x + n #Returns an anonymous function

f = make_incrementor(42)

f(0) # 42
f(1) # 43

Documentation string (docstring)

point

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

print(my_function.__doc__)

#output
# Do nothing, but document it.
# 
#     No, really, it doesn't do anything.

Function annotation (function annotation)

point

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

f('spam')

#output
# Annotations: {'ham': <class 'str'>, 'eggs': <class 'str'>, 'return': <class 'str'>}
# Arguments: spam eggs
# 'spam and eggs'

Coding style

point

Recommended Posts

Python control syntax, functions (Python learning memo ②)
Python class (Python learning memo ⑦)
Python module (Python learning memo ④)
[Python] Memo about functions
Python control syntax (memories)
Python exception handling (Python learning memo ⑥)
Python memo
python memo
Input / output with Python (Python learning memo ⑤)
Python memo
Python functions
python memo
python learning
Python memo
Interval scheduling learning memo ~ by python ~
"Scraping & machine learning with Python" Learning memo
Python memo
Python memo
Python & Machine Learning Study Memo: Environment Preparation
Python numbers, strings, list types (Python learning memo ①)
[Learning memo] Basics of class by python
[Control engineering] Graphing transfer functions using Python
Python data structure and operation (Python learning memo ③)
[Python] Chapter 05-02 Control Syntax (Combination of Conditions)
Python standard library: second half (Python learning memo ⑨)
Python & Machine Learning Study Memo ③: Neural Network
Python & Machine Learning Study Memo ④: Machine Learning by Backpropagation
Python & Machine Learning Study Memo ⑥: Number Recognition
Python standard library: First half (Python learning memo ⑧)
[Python] Memo dictionary
LPIC201 learning memo
[Python] Learning Note 1
python beginner memo (9.2-10)
Python learning notes
Django Learning Memo
python beginner memo (9.1)
python learning output
Python learning site
★ Memo ★ Python Iroha
Python learning day 4
with syntax (Python)
[Python] EDA memo
Python Deep Learning
Python 3 operator memo
Python learning (supplement)
#Python basics (functions)
[Beginner] Python functions
Deep learning × Python
Install Python Control
[Memo] Machine learning
[My memo] python
Python3 metaclass memo
[Python] Basemap memo
Python Easy-to-use functions
Python syntax-control syntax
Python basics: functions
Python beginner memo (2)
python learning notes
[Python] Numpy memo
Python & Machine Learning Study Memo ⑤: Classification of irises
Python & Machine Learning Study Memo ②: Introduction of Library