This time is a learning memo about control syntax and functions.
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")
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']
point
range (10)
are exactly the indexes for each item in a sequence of length 10 (the sequence can be indexed repeatedly).
#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
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
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
point
global
statement)None
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
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]
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
** name
, this argument receives a dictionary* name
formatdef 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
point
* args
format, all formal arguments after this can only be used as keyword arguments, not as positional arguments.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
point
* args
format>>> list(range(3, 6))
[3, 4, 5]
>>> args = [3, 6]
>>> list(range(*args))
[3, 4, 5]
**
operator.>>> 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 !
point
lambda
def make_incrementor(n):
return lambda x: x + n #Returns an anonymous function
f = make_incrementor(42)
f(0) # 42
f(1) # 43
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.
point
__annotations__
attribute and has no effect on other parts of the function->
before the colon at the end of the def statement and between it and the formal argument list.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'
point
Recommended Posts