--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.
--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
--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
--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!
--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
--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
-** 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
#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
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
If you put a break statement in the for statement, you can stop the loop in the same way as while.
If you put continue in the for statement, it jumps to the next iteration in the same way as while.
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?
--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'}
--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]
** Comprehension ** is a format that allows you to compactly create a Python data structure from one or more iterators.
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
--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}
--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}
--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
[]
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
--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'}
--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'}
#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']
--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')
-** 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)
--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
--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!'
--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'
--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!
--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
--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
--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'
--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
--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
--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
>>> if guess_me<7:
... print("too low")
... elif guess_me>7:
... print("too high")
... elif guess_me==7:
... print("just right")
...
just right
>>> 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!
>>> list=[3,2,1,0]
>>> for x in list:
... print(list[x])
...
0
1
2
3
>>> list=[number for number in range(10) if number%2==0]
>>> list
[0, 2, 4, 6, 8]
>>> 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}
>>> odd= {number for number in range(10) if number%2==1}
>>> odd
{1, 3, 5, 7, 9}
>>> 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
>>> def good():
... print(["H","R","Hermione"])
...
>>> good()
['H', 'R', 'Hermione']
#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
>>> 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
#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
>>> titles=["C","B","A"]
>>> plots=["D","W"]
>>> movies=dict(zip(titles,plots))
>>> movies
{'C': 'D', 'B': 'W'}
There was a lot of review volume in Chapter 4. It took me a day.
"Introduction to Python3 by Bill Lubanovic (published by O'Reilly Japan)"
Recommended Posts