Python-Steuerungssyntax, Funktionen (Python-Lernnotiz ②)

Dieses Mal ist ein Lernprotokoll über Steuerungssyntax und -funktionen.

if-Anweisung

Punkt

#Sie können auf eine solche Eingabe warten
x = int(input("Bitte geben Sie eine Ganzzahl ein: "))

if x < 0:
    x = 0
    print ("Negative Zahl ist Null")
elif x == 0:
    print("Null")
elif x == 1:
    print("Einer")
else:
    print("Mehr")

zur Aussage

Punkt


#Messen Sie die Länge einer Zeichenfolge
words = ['cat', 'window', 'defenstrate']
for w in words:
    print(w, len(w))

#Ausgabe
# cat 3
# window 6
# defenstrate 11

#Durchlaufen Sie die Slice-Kopie der gesamten Liste
words = ['cat', 'window', 'defenstrate']
#Machen Sie eine flache Kopie der Liste
for w in words[:]:
    if len(w) > 6:
        words.insert(0, w)
print(words)

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

range () Funktion

Punkt


#Iteration nach Reichweite
for i in range(5):
    print(i)

#Ausgabe
# 0
# 1
# 2
# 3
# 4

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

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

break and continue-Anweisungen, sonst Klausel in der Schleife

Punkt


for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print(n, 'equals', x, '*', n//x)
            break
    else:
        #Dies hängt sonst von ab
        #Wenn Sie den Bruch in der Schleife nicht finden können
        print(n, 'is a prime number')

#Ausgabe
# 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-Anweisung

Punkt

while True:
    pass #Mach nichts Strg+Warten Sie, bis Sie mit C fertig sind

#Generieren Sie die kleinste Klasse
class MyEmptyClass
    pass

#Funktionsdefinition
def initLog(*args):
    pass #Nach der Implementierung löschen


Funktionsdefinition

Punkt

def fib(n):
    """Zeigen Sie Fibonacci-Serien bis zu n an"""
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a+b
    print()

fib(2000)

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

Weiter zur Funktionsdefinition

Standardwert des Arguments

Punkt

#Beispiel ①
i = 5

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

i = 6
f()

#Ausgabe
# 5

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

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

#Ausgabe
# [1]
# [1, 2]
# [1, 2, 3]

Schlüsselwortargument

Punkt

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

#Sie können eines der folgenden Formulare aufrufen
parrot(1000)                                         #1 Positionsargument
parrot(voltage=1000)                                 #1 Schlüsselwortargument
parrot(voltage=100000000, action='VOOOOOM')          #2 Schlüsselwortargumente
parrot(action='VOOOOOOOM', voltage=1000000)          #2 Schlüsselwortargumente
parrot('a million', 'bereft of life', 'jump')        #3 Positionsargumente
parrot('a tousand', state='pushing up the daisies')  #1 Positionsargument 1 Schlüsselwortargument

#Der nächste Anruf ist ungültig
# parrot()                     #Fehlende erforderliche Argumente
# parrot(voltage=5.0, 'dead')  #Nicht-Keyword-Argument nach Keyword-Argument
# parrot(110, voltage=220)     #Das gleiche Argument zweimal gegeben
# parrot(actor='John Cleese')  #Unbekanntes Schlüsselwortargument
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")

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

Liste der optionalen Argumente

Punkt

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

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

#Ausgabe
# earth/mars/venus

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

#Ausgabe
# earth.mars.venus

Argumentliste entpacken

Punkt

>>> 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-Ausdruck

Punkt

def make_incrementor(n):
    return lambda x: x + n #Gibt eine anonyme Funktion zurück

f = make_incrementor(42)

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

Dokumentzeichenfolge (docstring)

Punkt

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

print(my_function.__doc__)

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

Funktionsanmerkung (Funktionsanmerkung)

Punkt

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

f('spam')

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

Codierungsstil

Punkt

Recommended Posts

Python-Steuerungssyntax, Funktionen (Python-Lernnotiz ②)
Python-Klasse (Python-Lernnotiz ⑦)
Python-Modul (Python-Lernnotiz ④)
[Python] Memo über Funktionen
Python-Steuerungssyntax (Denkmal)
Behandlung von Python-Ausnahmen (Python-Lernnotiz ⑥)
Python-Memo
Python-Memo
Eingabe / Ausgabe mit Python (Python-Lernnotiz ⑤)
Python-Memo
Python-Funktionen
Python-Memo
Python lernen
Python-Memo
Abschnittsplanung Lernnotiz ~ von Python ~
"Scraping & maschinelles Lernen mit Python" Lernnotiz
Python-Memo
Python & Machine Learning Study Memo: Vorbereitung der Umgebung
Python-Zahlen, Zeichenfolgen, Listentypen (Python-Lernnotiz ①)
[Lernnotiz] Grundlagen des Unterrichts mit Python
[Steuerungstechnik] Grafische Darstellung der Übertragungsfunktionen von Python
Struktur und Betrieb der Python-Daten (Python-Lernnotiz ③)
[Python] Kapitel 05-02 Steuerungssyntax (Kombination von Bedingungen)
Python-Standardbibliothek: zweite Hälfte (Python-Lernnotiz ⑨)
Python & Machine Learning Study Memo ③: Neuronales Netz
Python & maschinelles Lernen Lernnotiz Machine: Maschinelles Lernen durch Rückausbreitung
Python & Machine Learning Study Memo ⑥: Zahlenerkennung
Python-Standardbibliothek: Erste Hälfte (Python-Lernnotiz ⑧)
LPIC201 Studiennotiz
[Python] Lernnotiz 1
Python-Anfänger-Memo (9.2-10)
Python-Lernnotizen
Django Lernnotiz
Python-Anfänger-Memo (9.1)
Python-Lernausgabe
Python-Lernseite
★ Memo ★ Python Iroha
Python-Lerntag 4
mit Syntax (Python)
[Python] EDA-Memo
Python Deep Learning
Python 3-Operator-Memo
Python-Lernen (Ergänzung)
# Python-Grundlagen (Funktionen)
[Anfänger] Python-Funktionen
Deep Learning × Python
Installieren Sie Python Control
[Memo] Maschinelles Lernen
[Mein Memo] Python
Python3-Metaklassen-Memo
[Python] Grundkarten-Memo
Python Einfach zu bedienende Funktionen
Syntax zur Steuerung der Python-Syntax
Python-Grundlagen: Funktionen
Python-Anfänger-Memo (2)
Python-Lernnotizen
[Python] Numpy Memo
Python & Machine Learning Study Memo ⑤: Klassifikation von Ayame
Python & Machine Learning Study Memo Introduction: Einführung in die Bibliothek