[Introduction to Python3 Day 8] Chapter 4 Py Skin: Code Structure (4.1-4.13)

4.1 Comment by

--Comments with "#" in the text contained in the program are ignored by the Python interprinter. --Since Python does not have multi-line comments, you must put # at the beginning of comment lines and comment sections.

4.2 Continuation of line by \

--If you put \ at the end of a line, Python will think that you haven't changed the line yet.


#If you want to make a long character string from a small character string, there is a method to make it little by little as follows.
>>> alphabet = ""
>>> alphabet +="abcdefg"
>>> alphabet +="hijklmnop"
>>> alphabet +="qrstuv"
>>> alphabet +="wxyz"

#If you use continuous characters, you can make it in one step without making it difficult to see.
>>> alphabet = "abcdefg" + \
...  "hijklmnop" +\
...   "qrstuv"+\
...     "wxyz"

#Line continuity is also required when a line spans multiple lines.
>>> 1+2+
  File "<stdin>", line 1
    1+2+
       ^
SyntaxError: invalid syntax
>>> 1+2\
... 3
  File "<stdin>", line 2
    3
    ^
SyntaxError: invalid syntax
>>> 1+2+\
... 3
6

4.3 Comparison by if, elif, else

--In Python, the code should be coherent within the section and work, so ** the indents must be the same size and aligned on the left edge. ** ** --The recommended style of PEP8 uses 4 spaces.


#A program that checks the contents of a disaster and displays appropriate comments
>>> disaster = True
>>> if disaster:
...  print("Woe!")
... else:
...  print("Whee!")
...
Woe!


>>> funny = True
>>> small = True
#If if funny is True, enter the if small test.
>>> if funny:
...     if small:
...      print(" It is a cat.")
...     else:
...      print(" It is a bear!")
... else:
...      if small:
...       print(" It is a skink!")
...      else:
...       print(" It is a human.Or a hairless bear.")
...
 It is a cat.


#If the test is divided into 3 or more types, if,elif(means else if),Use else.
>>> color ="puse"
>>> if color =="red":
...  print(" It is a tomato")
... elif color =="green":
...  print(" It is a green pepper")
... elif color =="bee purple":
...  print("I don't know what it is,but only bees can see it")
... else:
...  print("I've never heard of the color",color)
...
I've never heard of the color puse


>>> x =2
#Equivalence test
>>> x ==2
True
>>> x ==5
False
>>> 4 < x
False
>>> x<10
True
#The Boolean operator has a lower priority than the element to be compared.
#The Boolean operator is performed after the element to be compared is calculated first.
>>> 1<x and x <10
True
>>> 1<x or x <10
True
>>> 1<x and x >10
False
>>> 1<x and not x >10
True
>>> 1<x<10
True
>>> 1<x<10<377
True

4.3.1 What is True

--Everything listed below is considered False. --Everything else is considered True.

What is considered False value
Boolean value False
null None
Integer zero 0
Zero of float 0.0
Empty string " "
Empty list [ ]
Empty tuple ( )
Empty dictionary { }
Empty set set()

>>> some_list = []
>>> if some_list:
...  print("There's something in here")
... else:
...  print("Hey,it's empty!")
...
Hey,it's empty!

4.4 Iterative processing by while

--Use a loop when you want to do the same thing more than once.


#Initialization of count
#Compare the value of count with 5
#Increment count by 1(Addition)
>>> count =1
>>> while count <=5:
...  print(count)
...  count+=1
...
1
2
3
4
5

4.4.1 Breaking loop due to break

--Use break if you want to break the loop


#infinite loop
#input()Use a function to read the input line from the keyboard and assign it to stuff
#The input character is"q":If so, exit the loop.
#"q"Other than the above, the first character of the input character string is displayed in uppercase.

>>> while True:
...  stuff=input("String to capitalize[type q to quit]:")
...  if stuff == "q":
...     break
...  print(stuff.capitalize())
...
String to capitalize[type q to quit]:type
Type
String to capitalize[type q to quit]:untitarou
Untitarou
String to capitalize[type q to quit]:q

4.4.2 Start of next iteration with continue

-** Iteration ** is one iteration.


#input()Use a function to read the input line from the keyboard and assign it to value
#The input character is"q":If so, exit the loop.
#Set value to int type and assign to number
#If even, start the next iteration

>>> while True:
...  value=input("Integer,please [q to quit]:")
...  if value == "q":
...     break
...  number =int(value)
...  if number %2==0:
...     continue
...  print(number,"squared is",number*number)
...
Integer,please [q to quit]:1
1 squared is 1
Integer,please [q to quit]:2
Integer,please [q to quit]:3
3 squared is 9
Integer,please [q to quit]:q

4.4.3 Checking break by else


#Initialization of variable position
#If even"Found even numbers"And that number is displayed and break exits the while statement.
#The else clause is executed when the while section ends but the desired object is not found.(break checker)

>>> number =[1,3,5]
>>> position =0
>>> while position <len(number):
...  numbers=number[position]
...  if numbers%2 ==0:
...   print("Found even numbers",numbers)
...   break
...  position+=1
... else:
...  print("No even number found")
...
No even number found

Iterative processing with 4.5 for

Python frequently uses ** iterators (which retrieve and return elements one by one from lists, dictionaries, etc. for each iteration) **. That's because you can manipulate each element of a data structure without knowing it.


#while statement
>>> rabbits =["a","b","c","d"]
>>> current=0
>>> while current<len(rabbits):
...  print(rabbits[current])
...  current +=1
...
a
b
c
d

#for statement
>>> for rabbit in rabbits:
...  print(rabbit)
...
a
b
c
d

** Lists, strings, tuples, dictionaries, sets, etc. ** are Python's ** iterable (iterator-aware) objects **.

--When you process tuples and lists with for, one element is taken out at a time. --When a character string is processed with for, one character is generated at a time as shown below.


>>> word="cat"
>>> for letter in word:
...  print(letter)
...
c
a
t

--The key is returned when processing the dictionary with for.

>>> accusation ={"a":"ballroom","b":"weapon","c":"kowai"}
>>> for card in accusation:
...  print(card)
...
a
b
c

--If you want to iterate over the values, use the values () function of the dictionary.

>>> for value in accusation.values():
...  print(value)
...
ballroom
weapon
kowai

--Use the items () function if you want to return both keys and values in the form of tuples.

>>> for value in accusation.items():
...  print(value)
...
('a', 'ballroom')
('b', 'weapon')
('c', 'kowai')

--If you want to assign each element of the tuple to an individual variable, prepare two variables for for. "Key" is assigned to the first argument and "value" is assigned to the second argument.

>>> for card,contents in accusation.items():
...  print("Card",card,"has the contents",contents)
...
Card a has the contents ballroom
Card b has the contents weapon
Card c has the contents kowai

4.5.1 Canceled due to break

If you put a break statement in the for statement, you can stop the loop in the same way as while.

4.5.2 Start of next iteration with continue

If you put continue in the for statement, it jumps to the next iteration in the same way as while.

4.5.3 Checking break by else

Like while, for has an optional else to check if it ended normally. If break is not called, the else statement is executed.


>>> cheeses=[]
>>> for cheese in cheeses:
...  print("This shop has some lovely",cheese)
...  break
... else:
...  print("This is not much of a cheese shop,is it?")
...
This is not much of a cheese shop,is it?

4.5.4 Multiple sequence processing using zip ()

--You can use the zip function to ** process multiple sequences in parallel **. --zip () stops when it finishes processing the smallest sequence element.


#Creating a list
#Only desserts are longer than the other lists. No one gets pudding unless the other factors are lengthened.
>>> days =["Monday","Tuesday","Wednesday"]
>>> fruits=["coffee","tea","bear"]
>>> drinks=["coffee","tea","beer"]
>>> desserts=["tiamisu","ice cream","pie","pudding"]

#zip()Can be used to create tuples from elements with a common offset by tracing multiple sequences.
>>> for day,fruit,drink,dessert in zip(days,fruits,drinks,desserts):
...     print(day,":drink",drink,"- eat",fruit,"-enjoy",dessert)
...
Monday :drink coffee - eat coffee -enjoy tiamisu
Tuesday :drink tea - eat tea -enjoy ice cream
Wednesday :drink beer - eat bear -enjoy pie


#zip()The value returned by is not a tuple or list, but an iterable value that can be a tuple or list.
>>> english="Monday","Tuesday","Wednesday"
>>> french="Lundi","Mardi","Mercredi"
#List
>>> list(zip(english,french))
[('Monday', 'Lundi'), ('Tuesday', 'Mardi'), ('Wednesday', 'Mercredi')]
#Dictionary
>>> dict(zip(english,french))
{'Monday': 'Lundi', 'Tuesday': 'Mardi', 'Wednesday': 'Mercredi'}

4.5.5 Generating a numeric sequence with range ()

--You can use the range () function to return a numeric stream in the specified range. --range () is used in a format similar to a slice called range (start: end: step). If start is omitted, 0 will be the first. The only argument is end, and the last value created like a slice is the value of step-1. The default value of step is 1, but you can specify -1 to reverse the order. --Like zip (), range () returns an iterable object, so the return value needs to be iterated with for ... in or converted to a sequence such as a list.


#Create a range from 0 to 3
>>> for x in range(0,3):
...   print(x)
...
0
1
2
#List
>>> list(range(0,3))
[0, 1, 2]

#Create a range from 2 to 0
>>> for x in range(2,-1,-1):
...   print(x)
...
2
1
0
#List
>>> list(range(2,-1,-1))
[2, 1, 0]

#Take out even numbers from 0 to 10
>>> list(range(0,11,2))
[0, 2, 4, 6, 8, 10]

4.6 Comprehension

** Comprehension ** is a format that allows you to compactly create a Python data structure from one or more iterators.

4.6.1 List comprehension

A list of integers from 1 to 5 can also be created by adding elements one by one as shown below.


#append()Is added at the end.
>>> number_list=[]
>>> number_list.append(1)
>>> number_list.append(2)
>>> number_list.append(3)
>>> number_list.append(4)
>>> number_list.append(5)
>>> number_list
[1, 2, 3, 4, 5]

#range()You can also create it with a function and for.
>>> number_list=[]
>>> for number in range(1,6):
...     number_list.append(number)
...
>>> number_list
[1, 2, 3, 4, 5]

#range()You can also make it by directly converting the output of.
>>> number_list = list(range(1,6))
>>> number_list
[1, 2, 3, 4, 5]

The code using ** list comprehension ** is shown below.


#[expression for item in iterable]Basic format of
#The first number variable is the number of the loop execution result_For storing in list.
#The second number is part of the for statement
>>> number_list = [number for number in range(1,6)]
>>> number_list
[1, 2, 3, 4, 5]

#You can see that the first number is an expression.
>>> number_list = [number-1 for number in range(1,6)]
>>> number_list
[0, 1, 2, 3, 4]


>>> a_list=[]
>>> for number in range (1,6):
...     if number%2 ==1:
...       a_list.append(number)
...
>>> a_list
[1, 3, 5]

#[expression for item in iterable if condition]Format
>>> a_list = [number for number in range(1,6) if number %2 ==1]
>>> a_list
[1, 3, 5]


>>> rows =range(1,4)
>>> cols=range(1,3)
>>> for row in rows:
...     for col in cols:
...        print(row,col)
...
1 1
1 2
2 1
2 2
3 1
3 2

#Comprehensions can also be nested.
#It is output as a tuple.
>>> rows =range(1,4)
>>> cols=range(1,3)
>>> cells = [(row,col) for row in rows for col in cols]
>>> for cell in cells:
...     print(cell)
...
(1, 1)
(1, 2)
(2, 1)
(2, 2)
(3, 1)
(3, 2)

#row from tuple while iterating through the cells list,Pull out col.
>>> for row,col in cells:
...     print(row,col)
...
1 1
1 2
2 1
2 2
3 1
3 2

4.6.2 Dictionary comprehensive notation

--There is also a comprehension in the dictionary. --Basic format of {key_item: value_item for item in iterable}


#"letters"Take out the characters one by one from"letters"Count how many are included in, and letter the key and the number of counts_Store in counts
>>> word ="letters"
>>> letter_counts={x:word.count(x)for x in word}
>>> letter_counts
{'l': 1, 'e': 2, 't': 2, 'r': 1, 's': 1}

#Let's try words as a set.
>>> word ="letters"
>>> letter_counts={x:word.count(x)for x in set(word)}
>>> letter_counts
{'e': 2, 'l': 1, 's': 1, 't': 2, 'r': 1}

4.6.3 Set comprehension

--Basic format of {item for item in iterable} --A long version can be used even in a set.

>>> a_set={number for number in range(1,6) if number %3 ==1}
>>> a_set
{1, 4}

4.6.4 Generator comprehension

--There is no inclusion notation in tuples --Returns a generator object when you make a comprehension with ordinary parentheses --A generator is one of the methods to supply data to an iterator.


#Those between () are generator comprehensions
>>> number_thing = (number for number  in range(1,6))
#Returns a generator object.
>>> type(number_thing)
<class'generator'>
#Generator objects can be processed with a for statement.
>>> for number in number_thing:
...     print(number)
...
1
2
3
4
5

#List generator comprehension()If you wrap it in a call, it can behave like a list comprehension list comprehension notation.
>>> number_list=list(number_thing)
>>> number_list
[1, 2, 3, 4, 5]

#The generator can only be run once. The generator creates values one at a time on the spot and passes them to the iterator, so I don't remember the created values. Therefore, the generator cannot be used or backed up again.
>>> number_list=list(number_thing)
>>>
>>> number_list
[]

4.7 Functions

Programmers can do two things with a function.

--Function definition --Function call

To define a Python function, type def, write the function name, enclose the input arguments to the function in parentheses, and write (:) at the end.


#make_a_sound()When you call the function, Python executes the code in the definition. In this case, it outputs one word and returns control to the main program.
>>> def make_a_sound():
...     print("quack")
...
>>> make_a_sound()
quack

#A function that has no arguments but returns a value
>>> def agree():
...     return True
...
>>> agree()
True

#Test the return value using if.
>>> if agree():
...     print("Splendid!")
... else:
...     print("That was unexpected.")
...
Splendid!


>>> def echo(anything):
...     return anything+' '+anything
...
#echo()the function is"ss"It is called with the actual argument.
#This value is echo()It is copied to the formal argument "anithing" in and returned to the caller.
>>> echo("ss")
'ss ss'

--The value passed to a function when you call it is also called an argument.

-When calling a function with ** argument **, those values are copied to the corresponding ** parameter ** in the function.

>>> def commtentary(color):
...     if color == "red":
...       return " It is a tomoato."
...     elif color =="green":
...       return " It is a green pepper"
...     elif color =="bee purple":
...       return "I don't know what it is,but only bees can see it."
...     else:
...       return "I've never heard of te color"+ color+"."
...
#"blue"Call the commentary function with the actual argument.
>>> comment=commtentary("blue")
>>> print(comment)
I've never heard of te colorblue.

--The caller receives None unless the function explicitly calls return


>>> def do_nothing():
...   pass
...
>>> print(do_nothing())
None

--None is used when there is nothing to say. --None is false when evaluated as a Boolean value, but not the same as the Boolean False.


>>> def is_none(thing):
...     if thing is None:
...       print(" It is nothing")
...     elif thing:
...       print(" It is True")
...     else:
...       print(" It is False")
...


>>> is_none(None)
 It is nothing
>>> is_none(True)
 It is True
>>> is_none(False)
 It is False

#Integers and floats of zero, empty strings, empty lists, empty tuples, empty dictionaries, empty sets are False, but not equal to None.
>>> is_none(0)
 It is False
>>> is_none(0.0)
 It is False
>>> is_none(())
 It is False
>>> is_none([])
 It is False
>>> is_none({})
 It is False
>>> is_none(set())
 It is False

4.7.1 Positional arguments

--Position arguments are arguments that are copied to the formal arguments at the corresponding positions in order from the beginning.

>>> def menu(x,y,z):
...     return{"wine":x,"entree":y,"dessert":z}
...
>>> menu("aaa","bbb","ccc")
{'wine': 'aaa', 'entree': 'bbb', 'dessert': 'ccc'}

4.7.2 Keyword arguments

--Specify the name of the corresponding formal argument and specify the actual argument. --If you want to call a function with both positional and keyword arguments, you must first specify the positional arguments.


>>> def menu(x,y,z):
...     return{"wine":x,"entree":y,"dessert":z}
...
>>> menu("beef","bagel","bordeaux")
{'wine': 'beef', 'entree': 'bagel', 'dessert': 'bordeaux'}

#The actual argument is specified by specifying the formal argument.
>>> menu(y="beef",z="bagel",x="bordeaux")
{'wine': 'bordeaux', 'entree': 'beef', 'dessert': 'bagel'}
#If you want to use both positional and keyword arguments, specify the positional argument first.
>>> menu("frontenac",z="flan",y="fish")
{'wine': 'frontenac', 'entree': 'fish', 'dessert': 'flan'}

4.7.3 Specifying the default argument value


#Specifying the default argument value
>>> def menu(x,y,z="unchi"):
...     return{"wine":x,"entree":y,"dessert":z}
...
#"dessert"Only the argument is not specified, so the default argument is entered.
>>> menu("dunkelfelder","chiken")
{'wine': 'dunkelfelder', 'entree': 'chiken', 'dessert': 'unchi'}
#If you specify an argument, it will be used instead of the default value.
>>> menu("dunkelfelder","duck","doughnut")
{'wine': 'dunkelfelder', 'entree': 'duck', 'dessert': 'doughnut'}


>>> def buggy(arg,result=[]):
...     result.append(arg)
...     print(result)
...
>>> buggy("a")
['a']
#['ab']I want to...
>>> buggy("ab")
['a', 'ab']

#buggy()Result every time a function is called[]The point is to initialize it
>>> def buggy(arg):
...     result=[]
...     result.append(arg)
...     return result
...
>>> buggy("a")
['a']
#Worked correctly!!!!
>>> buggy("b")
['b']


#result=[]The if statement is used as, and the result is initialized.
>>> def nonbuggy(arg,result=None):
...     if result is None:
...         result = []
...     result.append(arg)
...     print(result)
...
>>> nonbuggy("a")
['a']
>>> nonbuggy("b")
['b']

4.7.4 * Tuple position arguments

--If you use * as part of a formal argument in a function definition, you can combine variable positional arguments into a tuple and set it to that formal argument. -It is customary to use args as a tuple formal argument when using *.


>>> def print_args(*args):
...     print("Positional argument tuple:",args)
...
>>> print_args()
Positional argument tuple: ()
#Appears as an args tuple
>>> print_args(3,2,1,"wait!","uh...")
Positional argument tuple: (3, 2, 1, 'wait!', 'uh...')

#If there are required arguments, at the end of the positional argument*By writing args, all positional arguments other than the required arguments can be combined into one.
>>> def print_more(x1,x2,*args):
...     print("Need this one",x1)
...     print("Need this one too",x2)
...     print("All the rest",args)
...
>>> print_more("cap","gloves","scarf","monocle","mustache wax")
Need this one cap
Need this one too gloves
All the rest ('scarf', 'monocle', 'mustache wax')

4.7.5 ** Dictionary of keyword arguments

-** can be used to combine keyword arguments into a single dictionary. --The name of the argument is the key of the dictionary, and the value of the argument is the value of the dictionary. --When using * args and ** kwargs to combine positional arguments, these two must be combined in this order.

>>> def print_kwargs(**kwargs):
...     print("Keyward arguments:",kwargs)
...
>>> print_kwargs(x="xx",y="yy",z="zz")
Keyward arguments: {'x': 'xx', 'y': 'yy', 'z': 'zz'}

**4.7.6 docstring

--Function You can add a document to the function definition by embedding a character string at the beginning of the main subject. This is called the function docstring.


>>> def echo(anything):
...     'echo returns the given input arguments'
...     return anything
...
#help()When you call a function, the docstring of the function is displayed.
>>> help(echo)
Help on function echo in module __main__:

echo(anything)
echo returns the given input arguments
(END)

4.7.7 Function as a full-fledged object

--Functions are also objects. --Functions can be used as elements in lists, tuples, sets and dictionaries. --Since the function is immutable, it can also be used as a dictionary key.


>>> def answer():
...     print(43)
...
>>> answer()
43
>>> def run_something(func):
...      func()
...
#answer()If you pass answer instead, you are using the function as the data type like any other data type.
>>> run_something(answer)
43


>>> def add_args(x1,x2):
...     print(x1+x2)
...
>>> type(add_args)
<class'function'>

#run with func as an object_something_with_Passing to args.
>>> def run_something_with_args(func,arg1,arg2):
...     func(arg1,arg2)
...
>>> run_something_with_args(add_args,5,9)
14


#Take any number of positional arguments and sum()The function calculates and returns the sum of them.
>>> def sum_args(*args):
...     return sum(args)
...


>>> def run_with_positional_args(func,*args):
...     return func(*args)
...
>>> run_with_positional_args(sum_args,1,2,3,4)
10

4.7.8 In-function function

--Functions can be defined within functions.


>>> def outer(a,b):
...     def inner(c,d):
...         return c+d
...     return inner(a,b)
...
>>> outer(4,7)
11
>>> def knights(s):
...     def inner(q):
...         return "%s" % q
...     return inner(s)
...
>>> knights("Ni!")
'Ni!'

4.7.9 Closure

--In-function functions function as closures. --Closers are functions that are dynamically generated by other functions, and you can remember or change the values of variables created outside that function.


#inner2()Does not request an argument and uses the argument s directly for the outer function.
#knights2()Returns the function name instead of calling inner2.

#inner2 is acting as a closure.
>>> def knights2(s):
...     def inner2():
...         return "%s" % s
...     return inner2
...
>>> a= knights2("Duck")
>>> b= knights2("Hasenpfeffer")
>>> type(a)
<class'function'>
>>> type(b)
<class'function'>

#These are functions, but they are also closures.
>>> a
<function knights2.<locals>.inner2 at 0x1006d6ef0>
>>> b
<function knights2.<locals>.inner2 at 0x1006d60e0>

#Calling these, the two closures remember the contents of the s they were making in knights2.
>>> a()
'Duck'
>>> b()
'Hasenpfeffer'

4.7.10 Anonymous function: Lambda function

--The lambda function is an anonymous function expressed in one statement. ――Effective in situations where you have to create a number of small functions and remember their names.


>>> def edit_story(words,func):
...     for word in words:
...         print(func(word))
...
>>> stairs = ["x","u","z","r"]
>>> def enliven(word):
...     return word.capitalize()+"!"
...
#It takes out characters from the list one by one and processes them with enliven.
>>> edit_story(stairs,enliven)
X!
U!
Z!
R!

#enliven()The function is so short that I replace it with lambda.
#This lambda takes one argument, word.
#":"The part from to the end is a function definition.
>>> edit_story(stairs,lambda word:word.capitalize()+"!")
X!
U!
Z!
R!

4.8 Generator

--A generator is an object that creates a Python sequence. --Generators are often the data source for iterators.


#The generator function returns the value in a yield statement instead of return.
>>> def my_range(first=0,last=10,step=1):
...     number=first
...     while number < last:
...         yield number
...         number +=step
...
#my_range is a normal function.
>>> my_range
<function my_range at 0x1009364d0>
>>> ranger=my_range(1,5)
#Returns a generator object.
>>> ranger
<generator object my_range at 0x100636ed0>
#Iterative processing by for can be performed on the generator object.
>>> for x in ranger:
...     print(x)
...
1
2
3
4

4.9 Decorator

--A decorator is a function that takes one function as input and returns another. --Create a decorator using: -* Args and ** kwargs --In-function function --Function as an argument --You can have multiple decorators for a function. The decorator closest to the function is executed first, then the decorator above it.


>>> def document_it(func):
...     def new_function(*args,**kwargs):
...         print("Running function:",func.__name__)
...         print("Positional arguments:",args)
...         print("Keyword arguments:",kwargs)
...         result =func(*args,**kwargs)
...         print("Result:",result)
...         return result
...     return new_function
... 
>>> def add_ints(a,b):
...     return a+b
... 
>>> add_ints(1,2)
3
>>> cooler_add_ints =document_it(add_ints)
>>> ccler_add_ints(1,2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'ccler_add_ints' is not defined
>>> cooler_add_ints(1,2)
Running function: add_ints
Positional arguments: (1, 2)
Keyword arguments: {}
Result: 3
3

#Just before the function you want to decorate@decorator_Add in name format.
>>> @document_it
... def add_ints(a,b):
...     return a+b
... 
>>> add_ints(1,2)
Running function: add_ints
Positional arguments: (1, 2)
Keyword arguments: {}
Result: 3
3

4.10 Namespace and scope

--A namespace is an area where the meaning of a particular name is uniquely determined and is independent of the same name as other namespaces. However, you can access other namespaces if needed. --The main part of the program defines the global namespace. Variables in this namespace are called global variables. --python provides two functions to access the namespace. --locals () returns a ** dictionary ** showing the contents of the local namespace. --globals () returns a ** dictionary ** showing the contents of the global namespace.


#The values of global variables can be referenced from within the function.
>>> animal="Z"
>>> def print_global():
...     print("inside print_global:",animal)
...
>>> print("at the top level:",animal)
at the top level: Z
>>> print_global()
inside print_global: Z

#An error occurs when trying to get the value of a global variable in a function and rewrite it.
>>> def changed_and_print_global():
...     print("inside change_and_print_global:",animal)
...     animal="wombat"
...     print("after the change:",animal)
...
>>> changed_and_print_global()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in changed_and_print_global
UnboundLocalError: local variable 'animal' referenced before assignment

#change_local()The function also has a variable called animal, but that variable exists in the function's local namespace.
>>> animal="Z"
>>> def change_local():
...     animal = "W"
...     print("inside change_local:",animal,id(animal))
...

#change_local()It can be seen that the animal variable in is different from the animal variable in the program.
>>> change_local()
inside change_local: W 4564475440
>>> animal
'Z'
>>> id(animal)
4564751344

#To access a global variable, you must explicitly use the global keyword.
>>> animal="Z"
>>> def change_and_print_global():
...     global animal
...     animal = "wombat"
...     print("inside change_and_print_global:",animal)
...
>>> animal
'Z'
>>> change_and_print_global()
inside change_and_print_global: wombat
>>> animal
'wombat'

#If you don't write global in your function, Python will use the local namespace and animal variables will be local. When the function is finished, the local variables disappear and disappear.
>>> animal="Z"
>>> def change_local():
...     animal = "wombat"
...     print("locals:",locals())
...
>>> animal
'Z'

#Returns a dictionary showing the contents of the local namespace.
>>> change_local()
locals: {'animal': 'wombat'}

#Returns a dictionary showing the contents of the global namespace.
>>> print("globals:",globals())
globals: {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class'_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'document_it': <function document_it at 0x110146290>, 'add_ints': 3, 'square_it': <function square_it at 0x110146440>, 'animal': 'Z', 'print_global': <function print_global at 0x1101464d0>, 'changed_and_print_global': <function changed_and_print_global at 0x1101465f0>, 'change_local': <function change_local at 0x110146950>, 'change_and_print_global': <function change_and_print_global at 0x110146830>}
>>> animal
'Z'

4.10.1 _ and __ in the name

--Names with two underscores at the beginning and end are reserved as variables used by Python.


>>> def amazing():
...     '''This is a great function
...See again'''
#The name of the function is the function of the system variable_name__(Basic format)
...     print("The name of this function:",amazing.__name__)
#docstring is a system variable function_doc__(Basic format)
...     print("docstring:",amazing.__doc__)
...
>>> amazing()
The name of this function: amazing
docstring:This is a great function
See again

4.11 Error handling and try, except

--It's a good practice to add exception handling wherever exceptions are likely to occur and let the user know what will happen.


#Program forced termination
>>> short_list=[1,2,3]
>>> position = 5
>>> short_list[position]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

#You should use try to enclose where exceptions are likely to occur, and use except to provide exception handling.
#The code in the try block is executed, and if an error occurs there, an exception is generated and the code in the except block is executed. If no exception occurs, the except block will not be executed.

>>> short_list=[1,2,3]
>>> position = 5
>>> try:
...     short_list[position]
... except:
...     print("Need a position between 0 and",len(short_list)-1,"but got",position)
...
Need a position between 0 and 2 but got 5


#Use except to catch all exceptions.
#If you want to know the detailed information, describe the basic format of except exceptiontype as name.

>>> short_list=[1,2,3]
>>> while True:
...     value=input("Position[q to quit]?")
...     if value =="q":
...         break
...     try:
...         position=int(value)
...         print(short_list[position])
...     except IndexError as err:
...         print("bad index:",position)
...     except Exception as other:
...         print("Something else broke:",other)
...
Position[q to quit]?1
2
Position[q to quit]?0
1
Position[q to quit]?2
3
Position[q to quit]?3
bad index: 3
Position[q to quit]?2
3
Position[q to quit]?two
Something else broke: invalid literal for int() with base 10: 'two'
Position[q to quit]?q

4.12 Creating your own exception

--You can define your own exception type.


#It's up to the parent class Exception to see what to display when an exception is generated.
>>> class OopsException(Exception):
...     pass
...
>>> try:
...     raise OopsException("panic")
... except OopsException as exc:
...     print(exc)
...
panic

4.13 Review assignment

4-1 Let's assign 7 to the variable guess_me. Next, if guess_me is less than 7, it will be displayed too low, if it is greater than 7, it will be displayed too high, and if it is equal, it will be displayed just right.


>>> if guess_me<7:
...     print("too low")
... elif guess_me>7:
...     print("too high")
... elif guess_me==7:
...     print("just right")
...
just right

4-2 Assign 7 to the variable guess_me and 1 to the variable start, and write a while loop that compares start and guess_me.


>>> while True:
...     if start<guess_me:
...         print("too low")
...     elif start==guess_me:
...         print("found it!")
...         break
...     elif start>guess_me:
...         print("oops")
...         break
...     start+=1
...
too low
too low
too low
too low
too low
too low
found it!

4-3 Use the for loop to display the values in the list [3,2,1,0].


>>> list=[3,2,1,0]
>>> for x in list:
...     print(list[x])
...
0
1
2
3

4-4 Create an even list of range (10) using list comprehensions.


>>> list=[number for number in range(10) if number%2==0]
>>> list
[0, 2, 4, 6, 8]

4-5 Let's make a dictionary called squares using dictionary comprehension. However, range (10) is used to return the key, and the square of the dictionary of each key is used as the value.

>>> squares={number:number*number for number in range(10)}
>>> squares
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

4-6 Let's make a set called odd from odd numbers of range (10) using set comprehension notation.


>>> odd= {number for number in range(10) if number%2==1}
>>> odd
{1, 3, 5, 7, 9}

4-7 Let's return "Got" for the value of range (10) using the generator comprehension.


>>> for thing in ("Got %s" %number for number in range(10)):
...     print(thing)
...
Got 0
Got 1
Got 2
Got 3
Got 4
Got 5
Got 6
Got 7
Got 8
Got 9

4-8 Let's define a function called good that returns the list ["H", "R", "Hermione"].


>>> def good():
...     print(["H","R","Hermione"])
...
>>> good()
['H', 'R', 'Hermione']

4-9 Let's define a generator function called get_odds that returns odd numbers from range (10). Also, use a for loop to find and display the third value returned.


#The generator function returns in yield.
>>> def get_odds():
...     for x in range(1,10,2):
...             yield x
...
#enumerate()By using a function, you can get the index number (count, order) at the same time as the elements of iterable objects such as lists (arrays) in the for statement. Index number,Can be obtained in the order of elements.
#Specify the offset from 1.
>>> for count,number in enumerate(get_odds(),1):
...     if count==3:
...         print("The third number is",number)
...         break
...
The third number is 5

4-10 Let's define a decorator that displays "start" when a function is called and "end" when it ends.


>>> def test(func):
...     def new_func(*args,**kwargs):
...         print("start")
...         result = func(*args,**kwargs)
...         print("end")
...         return result
...     return new_func
...
>>> @test
... def greeting():
...     print("Hello!")
...
>>> greeting()
start
Hello!
end

4-11 Let's define an exception called OopseException. Let's write this exception code and the code that catches this exception and displays "Caught an oops" to let us know what happened next.


#Definition of OopseException
>>> class OopseException(Exception):
...     pass
...
>>> raise OopseException()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
__main__.OopseException
>>> try:
...     raise OopseException
... except OopseException:
...     print("Caught an oops")
...
Caught an oops

4-12 Let's make a dictionary called movies using zip (). The dictionary shall be made by combining the lists titles = ["C", "B", "A"] and plots = ["D", "W"].


>>> titles=["C","B","A"]
>>> plots=["D","W"]
>>> movies=dict(zip(titles,plots))
>>> movies
{'C': 'D', 'B': 'W'}

Impressions

There was a lot of review volume in Chapter 4. It took me a day.

References

"Introduction to Python3 by Bill Lubanovic (published by O'Reilly Japan)"

Recommended Posts

[Introduction to Python3 Day 8] Chapter 4 Py Skin: Code Structure (4.1-4.13)
[Introduction to Python3 Day 13] Chapter 7 Strings (7.1-7.1.1.1)
[Introduction to Python3 Day 14] Chapter 7 Strings (7.1.1.1 to 7.1.1.4)
[Introduction to Python3 Day 15] Chapter 7 Strings (7.1.2-7.1.2.2)
[Introduction to Python3 Day 21] Chapter 10 System (10.1 to 10.5)
[Introduction to Python3 Day 3] Chapter 2 Py components: Numbers, strings, variables (2.2-2.3.6)
[Introduction to Python3 Day 2] Chapter 2 Py Components: Numbers, Strings, Variables (2.1)
[Introduction to Python3 Day 4] Chapter 2 Py Components: Numbers, Strings, Variables (2.3.7-2.4)
[Introduction to Python3, Day 17] Chapter 8 Data Destinations (8.1-8.2.5)
[Introduction to Python3, Day 17] Chapter 8 Data Destinations (8.3-8.3.6.1)
[Introduction to Python3 Day 19] Chapter 8 Data Destinations (8.4-8.5)
[Introduction to Python3 Day 18] Chapter 8 Data Destinations (8.3.6.2 to 8.3.6.3)
[Introduction to Python3 Day 7] Chapter 3 Py Tools: Lists, Tuples, Dictionaries, Sets (3.3-3.8)
[Introduction to Python3 Day 5] Chapter 3 Py Tools: Lists, Tuples, Dictionaries, Sets (3.1-3.2.6)
[Introduction to Python3 Day 6] Chapter 3 Py tool lists, tuples, dictionaries, sets (3.2.7-3.2.19)
[Introduction to Python3 Day 12] Chapter 6 Objects and Classes (6.3-6.15)
[Introduction to Python3 Day 22] Chapter 11 Concurrency and Networking (11.1 to 11.3)
[Introduction to Python3 Day 11] Chapter 6 Objects and Classes (6.1-6.2)
[Introduction to Python3 Day 23] Chapter 12 Become a Paisonista (12.1 to 12.6)
[Introduction to Python3 Day 20] Chapter 9 Unraveling the Web (9.1-9.4)
[Introduction to Python3 Day 1] Programming and Python
[Introduction to Python3 Day 10] Chapter 5 Py's Cosmetic Box: Modules, Packages, Programs (5.4-5.7)
[Introduction to Python3 Day 9] Chapter 5 Py's Cosmetic Box: Modules, Packages, Programs (5.1-5.4)
Introduction to Effectiveness Verification Chapter 1 in Python
Introduction to effectiveness verification Chapter 3 written in Python
Introduction to Effectiveness Verification Chapter 2 Written in Python
Rewrite Python2 code to Python3 (2to3)
Introduction to Python language
Introduction to OpenCV (python)-(2)
[Chapter 5] Introduction to Python with 100 knocks of language processing
[Chapter 3] Introduction to Python with 100 knocks of language processing
[Chapter 2] Introduction to Python with 100 knocks of language processing
[Technical book] Introduction to data analysis using Python -1 Chapter Introduction-
[Chapter 4] Introduction to Python with 100 knocks of language processing
Introduction to Python Django (2) Win
Introduction to serial communication [Python]
[Introduction to Python] <list> [edit: 2020/02/22]
Introduction to Python (Python version APG4b)
An introduction to Python Programming
Introduction to Python For, While
Convert python 3.x code to python 2.x
[Introduction to Udemy Python 3 + Application] 31. Comments
Introduction to Python Numerical Library NumPy
Practice! !! Introduction to Python (Type Hints)
Python learning memo for machine learning by Chainer Chapter 8 Introduction to Numpy
[Introduction to Python] <numpy ndarray> [edit: 2020/02/22]
[Introduction to Udemy Python 3 + Application] 57. Decorator
Introduction to Python Hands On Part 1
Introduction to Structural Equation Modeling (SEM), Covariance Structure Analysis with Python
Python learning memo for machine learning by Chainer Chapter 10 Introduction to Cupy
[Introduction to Python] How to parse JSON
[Introduction to Udemy Python 3 + Application] 56. Closure
Introduction to Protobuf-c (C language ⇔ Python)
[Introduction to Udemy Python3 + Application] 59. Generator
[Introduction to Python] Let's use pandas
I read "Reinforcement Learning with Python: From Introduction to Practice" Chapter 1
[Introduction to Python] Let's use pandas
[Introduction to Udemy Python 3 + Application] Summary
Python learning memo for machine learning by Chainer Chapter 9 Introduction to scikit-learn
Introduction to image analysis opencv python
I read "Reinforcement Learning with Python: From Introduction to Practice" Chapter 2