This article is from AI Academy's Python Grammar Quick Learning and Introduction to Python Programming. This is a partial modification based on the content. By reading this article, you will learn the basics of Python's basic grammar. If you have finished learning Python, please also use AI Academy where you can learn AI and machine learning for free (only some contents are charged, but almost all basic contents are free). ..
** AI Academy deals with learning content centered on the field of artificial intelligence (AI), and Python easily handles machine learning and deep learning in the field of artificial intelligence. Because you can. ** ** Also, in the article The 2018 Top Programming Languages, the programmer's annual income was the highest.
The 2018 Top Programming Languages Image Quote ** In addition to artificial intelligence technology, Python can be widely developed for web development and convenient business automation tools, and by learning Python, you will be able to do a wide range of things in one language. ** ** In addition, ** Python programming itself is simple, highly readable, and easy to learn **, so I highly recommend it. By all means, let's start with the basic grammar of Python at AI Academy and learn web development and machine learning!
This chapter focuses on quick learning of Python's basic grammar. If you want to write a program quickly, please use Google Colaboratory, which allows you to program Python without building a Python environment in your browser.
If you use Google Colaboratory, you do not need to build an environment. Also, this text deals with Python 3 series. If you want to create an environment where Python can run on your PC, read the [Build Python Environment](? Id = 2) text.
Programming language Python is a ** general-purpose programming language ** developed by Dutchman Guido van Rossum in 1991. ** One of the nice things about Python is that it can be written simply with less code. ** ** Python is a globally used language such as Google and DropBox.
The following is a rough outline.
For smartphone apps, etc., Python is not very suitable, so it is not listed. When developing a smartphone app (iOS or Android app), if it is an iOS app, Swift (iOS), For Android apps, you need to learn Java and Kotlin. For 3D and AR / VR applications, you need to use Unity (C #, etc.). In recent years, there is also a JavaScript framework for mobile apps developed by Facebook called React Native. If you are interested in the above contents, please check it out for yourself. (Skills to look up are very useful in programming.)
There are some changes, such as the print statement being changed to the print () function and the long type being abolished and treated as an int type. Python2 series will be end of support in 2020, so it is better to choose Python3 series if you are starting from now on.
PEP8
PEP8 is a Python coding convention. I hope you will read it each time you start programming with Python. PEP8
You can write comments in the code. By writing "#" at the beginning of the line, it is regarded as a comment until the end of the line. ** By writing a comment, everything is ignored when the code is executed, so you can use it as a memo about the code. ** ** In most business, multiple people create an application. Therefore, ** It is important to leave comments on a regular basis so that others can read the code easily. ** ** As much as possible, we recommend that you make a habit of writing comments in the program so that others can easily read it.
#This line is a comment. This line will not be executed.
print("Hello, Python")
#This line is a comment. This line will not be executed.
#This line is a comment. This line will not be executed.
Also, if you have the spare capacity, please execute the above program and check that the commented description is not displayed.
Character strings are enclosed in double quotation marks "" "or single quotation marks"'". Characters enclosed in single quotation marks are called" strings "in the programming world. ** The string must be enclosed in single quotes "'" or double quotes "" ". ** ** In Python3, the output result is the same regardless of which one you enclose. Also, when outputting a character string, if you do not enclose it in "'" or "" ", the code will not work. If you have the spare capacity, try issuing an error (Syntax Errror) to prevent the code from working. Here, if you do not enclose it with "'" or "" ", an error will occur and you can understand it better if you confirm that it does not work.
・ Difference between single quotation mark "'" and double quotation mark "" ", proper use -About the type of error code (for example, SyntaxError)
In programming, you can also handle "numerical values". Unlike strings, it does not need to be enclosed in quotation marks. ** Please note that if you enclose a number in quotation marks or double quotation marks, it will become a character string. ** ** Details will be explained in detail in the next chapter, "Variables and Data Types". In addition, you can perform four arithmetic operations by using symbols such as "+", "-", "/", and "%". Being able to perform four arithmetic operations makes it possible to create programs similar to calculators.
print(10) #Numbers do not need to be quoted.
print(10 + 5) #Adding
print(5 - 2) #Pulling
print(10 / 2) #Breaking
print(10 % 5) #Seeking too much
#Change priority
#Normally+When-than*Or/Has a higher priority,()で囲むこWhenで優先度を変えるこWhenができます。
print((20 - 5) // 3) # 5
Now let's run the above program. From top to bottom
python
10
15
3
5.0
0
It is okay if you can confirm that is output. Next, I will explain about the fact that the output result of division is a decimal point. For Python2, for example, 10/2 is 5, whereas It will be 5.0 for 3 series. This is because the 2nd system is truncated, while the 3rd system is not. If you want to truncate in 3 series like 2 series, you can do it with print (10 // 2).
Now, what if we run the following code?
print(10 + 5)
print('10 + 5')
Did print () on the first line print 15 and 2 print 10 + 5? In 1, the result of adding numbers is returned, while in 2, it is the character string "10 + 5". If you enclose it in "'" or "" ", it is interpreted as a character string and" 10 + 5 "is output as it is. In programming, strings and numbers are treated as completely different things. Details will be explained in the next chapter, "Variables and Data Types". Here, it's okay if you know that ** numbers are treated as strings by enclosing them in double or single quotes. ** **
** A variable is a name tag attached to a price. ** ** You can give a value multiple names (see one value from multiple variables). Also, use variables with names. This name is called the variable name.
lang = "Python" #Assign the string Python to the variable lang
The name of the variable (lang) can be decided freely. The word assignment has come up, but ** assignment means putting the value on the right side into the variable on the left side. ** ** Also, in Python, ** variable names are case sensitive. ** ** Then, the value held in the ** variable is held until the program ends. ** ** When you exit the program, the data in memory is also erased, so if you want to keep the data, you need to save it as a database or file.
var = "var"
Var = "Var"
print(var) #Output as var
print(Var) #Output as Var
#When two words are continued when naming a variable in Python
lowercase_underscore = "lowercase_underscore" #Recommendation
lowercaseunderscore = "lowercase_underscore" #not recommended
hello_world = "Hello, World" #Recommendation
helloworld = "Hello, World" #not recommended
#As mentioned above, variable names are all lowercase and underlined when connecting two or more words.(_)It is recommended to use.
#You can also define variables in a deprecated way. However, the program does not give an error, but use the recommended method.
Compare the program that does not use variables with the program that uses them. Here, I would like you to know how useful variables are. First, let's look at a program that does not use variables.
print(15 + 1)
print(15 - 2)
print(15 * 3)
print(15 / 4)
print(15 % 5)
Now rewrite 15 to 220. In this case, it will be necessary to rewrite all 5 print parts written as 15 to 220. It's not that hard with just 5 lines, but what about 100 or 1000 lines, for example? Changing one by one can be a daunting task.
That's when variables come in handy. If the variable x was defined from the beginning, All you have to do is replace x = 15 with x = 220.
x = 220
print(x + 1)
print(x - 2)
print(x * 3)
print(x / 4)
print(x % 5)
** By using variables, what needed to be modified for 5 lines earlier can be changed by changing only one place. ** ** Variables are convenient, so let's use them.
** A constant is a value whose value cannot be changed. ** ** Variables can change their value later, but constants cannot. However, Python does not have a syntax for defining constants, so when defining with a constant intent, it is common to define variable names in all uppercase letters **. If you come across a variable in uppercase, it's best not to rewrite the value. Python constants are also explained in Python's Coding Standards PEP8 (Official).
** Words that cannot be used in function names or variable names are called reserved words. ** ** If you use reserved words, you will get a syntax error. In Python3 series, there are about 30.
The following are all reserved words in Python 3.6 series, so they cannot be used for variable names, etc.
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
First, let's take a bird's eye view of data types in Python. In this chapter, we will focus on the integer type, string type, list type, and dictionary type shown below.
Depending on the programming language, when declaring a variable, it is necessary to make a "type declaration (declaration that this variable will store this type)". For example, other programming languages (such as Java and C) require type declarations. However, Python variables don't require type declarations, so you can put any type in a variable.
x = 5
print(x) #5 is output.
x = "Python" #Can be assigned without problems.
print(x) #Output as Python.
So far, we've seen values like "strings" and "numeric values." These are called "data types" and come in many varieties. The main types are integer type, string type, dictionary type, and list type.
** Enclose in double quotes ("and") or single quotes ('and') to get a string. ** ** There are three types of description methods as follows.
# 1)Single quotation
str1 = 'Hello World'
# 2)Double quotation
str2 = "Hello World"
# 3)Triple-double quotation
str3 = """Hello World
Hello Python"""
** In Python, there is no clear distinction between double quotes ("and") and single quotes ('and') when defining a string type, so use whichever you like to define the string type. I hope you can. ** **
x = '1' #String type
Furthermore, in the character string type, you can use both + and , When + is used between strings, it means ** join **, and multiple strings can be expressed as one string. You can use the asterisk symbol () to ** iterate ** a string.
Let's actually check each one.
#Join
a = "hello " #After joining, a half-width space is added at the end to make it easier to see.
b = "world"
print(a + b) # hello world
The following is an example of using *.
#Iterative
a = "hello"
print(a * 3) # hellohellohello
Let's write the following program and actually execute it.
print("Hello" + "World") # +Concatenate strings with
name = "Tom"
print("My name is " + name)
age = 24
#The following is a program that causes an error by concatenating character string types and numeric types with different data types.
print("My name is " + name + "My age is " + age) #This line will result in an error
# TypeError: Can't convert 'int' object to str implicitly
Then, ** TypeError: Can't convert'int' object to str implicitly ** is displayed. In this way, ** If you concatenate a string type and a numeric type with different data types, an error will occur. ** ** Therefore, to avoid this error, by converting the numeric type to the character string type, it will be treated as a concatenation of character strings and can be concatenated. Changing the ** data type in this way is called "type conversion" or "casting". ** ** ** Use str () to convert a numeric type to a string type. ** **
name = "Tom"
age = 24
print("My name is " + name + "My age is " + str(age))
#Earlier, I converted the numeric type to the string type, but on the contrary, I can also convert the string type to the numeric type.
#In that case, use "int".
string_price = "1000"
price = 500
total_price = int(string_price) + price
print(total_price) # 1500
This section describes list types.
The list type is one of the most important data types, so be sure to handle it properly.
Now, ** variables can manage only one data, but list types can manage multiple data (variables). ** **
In other languages it is also called an array.
Python lists do not require a type definition to store.
Use a list when you want to manage multiple data.
list is declared in the form array name = ["x", "y", "z"]
.
** Please note that the contents of the list start counting from the left, starting from 0 instead of 1. ** **
The numbers attached to the contents of this ** list are called subscripts (soeji) or indexes. ** **
** You can add an element to the end of the list by using append (). ** **
li = []
li.append("python)
print(li) # ['python']
li.append("php")
print(li) # ['python', 'php']
Dictionary type (dictionary type) is a data type that holds a pair of Key and Value.
Next is the dictionary syntax.
python
Dictionary name= {"Key" : "value",・ ・ ・}
** The list type has index numbers starting from 0 and the values are stored in order from 0, but the dictionary type uses {}. ** ** In that respect, it is written in a similar way to the dictionary type, but the dictionary type is not assigned a value from index 0. Therefore, ** lists can access values by index number, while dictionary types can access values by any key string. ** **
Let's first look at a simple program.
python
profile = {"name": "tani", "email": "[email protected]" }
print(profile["name"]) # tani
#Add new element
profile["gender"] = "male"
#Dictionary type with new elements added(profile)Output
print(profile)
So far you have learned the list type and the dictionary type, but what is the difference between the two? That is ** the elements are accessed differently **. The list type accesses the element by index (subscript), while the dictionary type accesses the element by key (string or number). It also differs in that the ** list type uses [], but the dictionary type uses {}. ** **
So what do the two have in common? What they have in common is that both list and dictionary types can store elements such as different data types (int and str). ** ** In addition, the elements can be rewritten.
The program is processed from top to bottom. Describe the processing method with a fixed grammar. In this chapter, you will learn if statements, Loop statements, etc., and learn how to control the flow of the program.
The basic flow of the program flows from top to bottom.
If the above figure is written in a Python program, it will be as follows, for example.
When executed, the following contents will be output in order.
First process
Next process
Last processing
** In other words, basically the program flows from top to bottom in the order in which it is written. ** **
In Python, the process is summarized by indentation. This indentation is a big feature of Python. Basically, four half-width spaces (or tab keys) play the role of indentation, but in Python grammar, Many syntaxes have a colon ":" at the end. (Conditional branch statement (if, elif, else), for statement, while statement, function, class definition)
It's a Python rule that you need to indent if you see a: at the end. For example, see the following as a sample program with:. In this chapter, we will explain ** if statements and for statements **, etc., so you do not have to understand the meaning of the following programs at this stage. Once you see:, understand that you need to indent.
for i in range(10):
if i%2==0:
print("{} is even.".format(i))
else:
print("{} is odd.".format(i))
#Output result
# 0 is even.
# 1 is odd.
# 2 is even.
# 3 is odd.
# 4 is even.
# 5 is odd.
# 6 is even.
# 7 is odd.
# 8 is even.
# 9 is odd.
In programming, processing is divided according to whether a certain condition is met. For example, "changing grades (processing) depending on test scores (conditions)" can also be expressed by conditional branching. The syntax is as follows:
#note)Note that this code doesn't work.
if condition A:
Execute if condition A is True
elif condition B:
Execute if condition A is False and condition B is True
else:
Execute if both conditions A and B are False
If you use an if statement, you can express the process of "if XX, do ☓☓" by conditional branching. For example, if the test score is 78 points or more, the program that outputs pass is as follows. Can be described as
#Specify a conditional expression after if, and write the processing to be executed when the condition is satisfied on the next line.
score = 80
if score > 78: #Comparison operator>I am using. Comparison operators are described below.
print("Passed")
** In conditional expressions, the symbol "comparison operator" is often used to compare two values. ** ** Comparison operators include operators as shown in the image below. Use == to indicate whether the right and left sides are equal. Also, use! = To indicate whether the right and left sides are not equal.
** The conditional part is written as "if conditional expression:". ** ** Note that if you forget to add the colon at the end of the line, an error will occur.
score = 80
if score > 78: #Comparison operator>I am using.
print("It is a pass. Congrats!")
else:
print("failure. Let's do our best next time.")
score = 100
if score == 100:
print("Perfect score")
elif score > 85:
print("Pass!")
else:
print("failure. Let's do our best next time.")
In Python, indentation of code (4 or 2 indents / half-width spaces) directly affects the operation of the program, so be careful of indentation.
In most programming languages, the basis of control syntax is loops. A loop is a control syntax for executing the same code multiple times. It is often used when you want to perform the same processing for each element of the list.
Let's look at the loop processing by the for statement. The format of the for statement is as follows.
#for Loop variable in list name:
#Process to be executed
for i in ["apple", "banana", "melon"]:
print(i)
#Output result
# apple
# banana
# 3 melon
The list is stored in the variable i in the loop and it is printed. I will explain in detail. First, the first element, apple (0th subscript), is assigned to the variable i and printed by print (i). Next, banana is fetched, assigned to i, and the last melon is also assigned to i and output. Since all the elements of the list have been fetched, the processing of this for statement ends at that point.
The ** range () function ** is often used to iterate a certain number of times with a for statement.
The range () function has the following roles:
range (x): Returns a list of serial numbers from 0 to x-1 range (x, y): Returns a list of serial numbers from x to y-1
For example, using range (), a program that repeats 0 to 9 a total of 10 times is as follows.
for i in range(10):
print(i)
#Output result
# 0
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
Let's look at other iterative examples. It's a little long, but please read it carefully.
data = [20, 40, 60, 88]
for d in data:
print(d)
#Output result
# 20
# 40
# 60
# 88
# (1)
sum_d = 0
for d in data:
# *=You can also call it.
sum_d += d # sum_d = sum_d +It is a writing style that omits d.
print(sum_d) #208 is output. 20+ 40 + 60 +The total number of 88.
#Output result
# 208
#The for statement can use else.
sum_d = 0
# (2)
for d in data:
sum_d += d
#When the loop is over, you can process what you want to process once.
else:
print(sum_d)
#Output result
# 208
#In Python, you can use else in the loop of the for statement seen here and the While statement seen later.
#If you write else, the inside of else will be processed when the loop ends.
#upper(1)When(2)The difference is whether or not you are using else, but the output is the same.
##break and continue
#continue skip once
for i in range(10):
if i == 3:
continue
print(i)
#Output result
# 0
# 1
# 2
# 4
# 5
# 6
# 7
# 8
# 9
#break process ends
for i in range(10):
if i == 3:
break
print(i) #Output 0 1 2
#Output result
# 0
# 1
# 2
#Note that if you use "break" when using the else you saw earlier with the for statement, the processing inside the else will not be executed.
#In this case, in the list"f"Since there is, found is output,
3 not found in else is not output.
data = [1, 2, 3, 4, 5, "f"]
for x in data:
if x == 'f':
print('found')
break
else:
print('not found') #In the case of this sample, else processing is not executed!
#Output result
# found
python for is a mechanism called iterator, Tuples, strings, dictionaries, etc. can also be used as keys.
for char in "hello":
print(char)
# h
# e
# l
# l
# o
You may want to know the index number while processing the elements of the list in order. In that case, use ** enumerate () **.
for index, name in enumerate(["apple", "banana", "melon"]):
print(index, name)
# 0 apple
# 1 banana
# 2 melon
Also, by combining list () and range (), you can concisely describe a list with elements from 1 to 100 as follows.
print(list(range(101)))
#Output result
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
To loop the dictionary type data, write as follows.
python
data = {"tani": 21, "kazu": 22, "python": 100}
for key, value in data.items():
print("key: {} value: {}".format(key, value))
# key: tani value: 21
# key: kazu value: 22
# key: python value: 100
** The while statement repeats the loop until certain conditions are met. ** ** The image is like a loop all the time between ~, and I use it less often than for, If you want to explicitly perform an infinite loop, describe the loop processing in while.
#Repeat until n reaches 10
n = 0
while n < 10:
print(n)
n += 1 # +Don't forget to do 1.
#Output result
# 0
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
** If you do not write n + = 1 or n = n + 1, you will end up in an infinite loop. ** ** Once in an infinite loop, press Ctrl + c to quit. Be careful not to get into an infinite loop.
By the way, if you want to intentionally make an infinite loop, write as follows.
#Since it is an infinite loop, when executing the following program, Ctrl+Please end with c.
#Or terminal/Forcibly close (close) the command prompt.
while True:
print("infinite loop")
** List Comprehensions create new lists from existing lists and generators. ** ** For example, the following is a sample that describes a program for creating a list of numbers obtained by squaring each number from 1 to 10 in list comprehension notation.
result = [x**2 for x in range(1,11)]
print(result) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
#In a normal loop:
result = []
for i in range(1,11):
result.append(i**2)
print(result) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
** List comprehensions can be used not only to process elements retrieved from an existing list, but also to add them to a new list only if conditions are met. ** ** The advantage of inclusion notation is that you can write the process concisely and reduce the cost of calling additional methods such as new lists.
In addition to list comprehensions, there are also comprehensions that generate sets and dictionaries. ** In the case of set and dictionary comprehension, the order of output values may not be maintained depending on the generated value, so please be careful when using it. ** **
s = {x**2 for x in range(1,6)}
print(s) # {1, 4, 9, 16, 25}
To write the dictionary comprehension, separate the key and value with a colon ":". Use {} as you would for a set comprehension.
d = {x*2:x**2 for x in range(1,11)}
print(d) # {2: 1, 4: 4, 6: 9, 8: 16, 10: 25, 12: 36, 14: 49, 16: 64, 18: 81, 20: 100}
Also, regarding the tuple inclusion notation, if you write as follows, it will be a generator. Note that if defined in (), it will not be a tuple comprehension. What is returned is the generator that creates the element.
t = (x for x in range(5))
print(t)
# <generator object <genexpr> at 0x1095c8eb8>
t = tuple([x for x in range(5)])
print(t) # (0, 1, 2, 3, 4)
** It is possible to receive input from the user by using input (). ** **
print("Please enter your name")
name = input()
print("What's your name"+name+"is")
** One caveat here is that the value received using input () is of type string. ** ** If you enter a numerical value, it will be cast to a character string type, so please be careful about the subsequent numerical processing. (Please cast with int () etc. once.)
The following is a program that outputs the contents input by the user infinitely. ** Assign the received value to the variable i and print i with print (). ** **
# Ctr-Exit with C.
while True:
print("Please Input!")
i = input()
print(i)
** A function is an instruction that receives certain data, executes certain unique processing, and returns the result **. There are ** 2 types of functions **, the first is ** original function ** and the second is ** standard function (built-in function) **. ** Proprietary functions can be created by programmers, thinking about names and processing as freely as programmers create variables. ** ** By combining functions, you can create programs efficiently. ** Standard functions are functions that Python has prepared from the beginning. ** ** Standard functions refer to print (), len (), input (), and so on. In the world of programming, it is a feature that you can freely define functions and call and use the created functions many times. This chapter focuses mainly on the grammar of ** proprietary functions **.
Let's start with ** Benefits **. Here are two main points. ** 1) The code becomes easier to understand ** The first advantage of using functions is that the code is easier to understand. Not only will it be easier to see by grouping each function, but debugging will also be more efficient. ** 2) Functions can reduce code duplication. ** ** Code maintainability is improved. Next is ** Disadvantages **, but if you explain in detail, you can pick up some, The disadvantages of that are not so many. Therefore, if you make a habit of actively creating and using functions, the range of programming will expand.
As an explanation of the original function, we will actually create the function. (* Creating a function is called defining a function.) Use the keyword ** def ** to define the function.
#note)Please note that this code does not work due to syntax.
def function name():
#Indent(Make sure to indent)!
#processing
Now, let's create a hello function that just outputs hello! Based on the above basic syntax. hello is the function name, and the indented line describes the definition of the processing of the hello function.
#The indent is for 4 half-width spaces.
#Below, hello()This is a sample that defines a function.
def hello():
print("hello!")
** Like variable names, function names can be defined with any name you like, as long as you don't use ["reserved words"](? Id = 158 & section = reserved words). ** ** In the previous program, I just defined the hello function, so I didn't call it. A function is not executed just by defining it, but can be used by actually calling it.
To execute (call) a function, you can call it by using ** function name () ** as follows. In the example below, the original function hello () is defined, and ** hello () ** is used to call (execute) it.
#Hello function definition
def hello():
print("hello!")
#Function call(Run)
hello() # hello!Is output
In the function definition, the function is just defined, so no processing is performed. To execute it, the call process is performed on the line with ** function name () **.
The function name can be freely named by the developer, but there are some caveats. As a caveat, when defining a function name, ** do not give the function name with reserved words, etc. **. Also, if you want to define a function name with two or more words when you define your own function name in Python, the style of inserting an underline (_) in lowercase letters is recommended as shown below.
def lowercase_underscore:
print("lowercase_underscore")
pass
Functions can also define functions that have no content processing, such as when defining an empty list type or an empty dictionary type. ** If you declare a function for the time being and do nothing to process the function, use "pass". ** **
#Define a test function with no processing
def test():
pass
The argument is ** the value given to the function when calling it **. It can be roughly divided into two types. ** 1) Formal argument (value received on the function definition side) ** ** 2) Actual argument (value given by the caller of the function) ** Below is a sample program of the function using arguments.
def say_hello(name):
print("Hello" + str(name) + "Mr.")
say_hello("Yamada") # こんにちはYamadaさん
Returns the data processed by the function to the caller. Later, we will look at it in detail in "Arguments and return".
I explained the return value (return value) earlier, but when the return statement is executed, the function ends and returns to the caller.
** return [return value (return value)] ** I will introduce the format of the function when there are arguments and return value (return value). If the return value is omitted, None will be the return value (return value). Also, if a return with no return value is executed in the function, the return value will be None.
#def function name(argument):
#processing
#return Return value
def adder(a, b):
return a+b
#Return is convenient when you want to keep the processing inside the function in a variable.
value = adder(5,10) #15 is assigned to the variable value
#The previous len()I will explain about the return value (return value) using.
#The variable data is a list with 5 elements from 1 to 5.
data = [1,2,3,4,5]
#Function len()By executing, element 5 of the list data will be the return value.
#The return value 5 is assigned to the variable value.
value = len(data)
print(value) # 5
If the above len () is illustrated, the flow will be as follows.
First, [1,2,3,4,5] is assigned to the variable data and it is defined as a list.
Then use the len () function to get the number of elements in the list data.
The obtained result is returned by return, and this
Sometimes the question of why you use return instead of print () doesn't really come to your mind. This section is easy for many programming beginners to trip over ** Explain the difference why you use return instead of print () in a function. ** ** ** As a major premise, print () and return are completely different things, so you need to be able to use them properly. ** ** First, the differences between the two are as follows. ** return aims to return a value ** ** print () aims to print the value ** ** In other words, using return means using it when you need to return a value **. ** Specifically, I will explain the correct example using return **. So, first look at the program below.
def adder1(a, b):
print(a+b)
def adder2(a, b):
return a + b
adder1(2, 4)
sum = adder2(2, 4)
print(sum)
In this program, it is difficult to convey the goodness of return, and I think that you can not feel the merit. This is because adder1 calls the function faster and outputs it inside the function. However, one of the commonly used uses of a function is to receive a calculation result with return and pass the value to another function again. The above method does not convey the goodness of return. Now, let's explain the correct program as an image of how to use return. Please read the sample program below.
def a(a,b):
return a + b
def b(a,b):
return a * b
x = a(2,2) #Substitute 4 for x
y = b(x, x) # 4 * 4
print(y) #16 is output
Like function b, the previous processing result x is also passed as an argument of function b. In this way, by performing a return, the calculation result can be temporarily stored in a variable. Furthermore, you can pass the value to another function and connect it to different processing. Also, passing to a function is an example of using return, but the point is that you can do some further processing on the return value (return value) without passing it to the ** function. ** If you just want to output (print) inside the function, you can output it with print (), but for functions that do not have a print function inside, the processed result is received by return (return value / return value). By assigning that value to a variable and passing the return value to another function, it will be possible to connect to another process again. As mentioned above, ** return is intended to return a value **, so it is assumed that the processing inside the function will be used as the return value even in the program after the processing inside the function. I will.
Now, let's take a sample function that uses return instead of print () inside the function.
def power(x):
return x*x
def absolute(x):
if (x < 0):
return -x
else:
return x
print(power(10)) # 100
print(absolute(-10)) # 10
The function allows you to set arguments if you do not specify them.
def func(a, b=5):
print(a)
print(b)
func(10,15) #10 and 15 are output
func(3) #3 and 5 are output
Here, in the above program, b = 5, but this is the default value of the argument. You can specify a default value for the argument. This function is a function that just outputs two arguments by giving two arguments, but If you pass only one argument, the second value will be output because the default value b is 5.
Now, think about the program below. When you run the program below, ['python','Python'] will be output in the last function call.
def sample(arg, arg_list=[]):
arg_list.append(arg)
print(arg_list)
sample('python')
sample('Python')
Q. When I execute this function, I want to return only the element passed as an argument each time. How can I actually fix it? ??
A. In this case, you need to fix it as follows.
def sample(arg):
arg_list = [] #List initialization
arg_list.append(arg)
print(arg_list)
sample('python') # ['python']
sample('Python') # ['Python']
The above initializes the list every time. After that, it appends the arg passed as an argument to an initialized empty list.
Scope is a pretty important part. It will be an important idea for programming in the future, so let's hold it firmly. ** The point is that the scope (effective range) differs depending on where the variable was created. ** **
First, let's look at an example of a normal function.
def add(x1):
x2 = 10 #Create a variable in a function(Local variables)
result = x1 + x2
print(result)
add(5) # 5 +10 to 15 output
Next is a program about the scope (scope) of variables.
def add(x1):
x2 = 10 #Create a variable in a function(Local variables)
result = x1 + x2
print(result)
add(5) # 5 +10 to 15 output
print(x2) #An error occurs here
When I run the above code, I get the error ** NameError: name'x2' is not defined **. ** This is because the variable x2 defined inside the function is a local variable and is valid only for the local variable or inside the function, so calling x2 outside the function will result in an error. ** **
A good solution is to define x2 outside the function. (* In addition to the scope of variables, the internal processing of functions has been modified to make it easier to understand.)
def add(x1,x2):
result = x1 + x2
return result
x1 = 5
x2 = 10
result = add(x1, x2) # 5 +10 to 15 output
print(result)
Alternatively, you can use ** global to use global variables ** within your function.
Declaration for accessing global variables in a function. There are local variables (functions defined inside the function definition) and global variables (variables defined outside the function definition).
glb = 0
def func1():
glb = 1
def func2():
global glb
glb = 5
print(glb) #0 is output
func1()
print(glb) #0 is output
func2()
print(glb) #5 is output
Let's look at another example.
var1 = 'Global variables'
def sample():
var2 = 'Local variables'
return (var1, var2)
print(sample())
The above example declares global and local variables respectively. The following sample is a program that modifies global variables from within a function.
var1 = 'global'
def sample():
global var1
var1 = 'Changed to local'
sample() #Change global variable var1 inside function
print(var1) #Changed to local
Based on your favorite text editor and terminal (command prompt), load and use your own module. Therefore, in the case of Jupyter Notebook and Google Colab, the programs described in this chapter will not work, so please try as follows.
Also, please check the link below for how to run it on Colab. Run on YouTube video / Colab
Create fortune.py on your PC. Next, from Colab's left menu (press>), you'll see a table of contents, code snippets, and files, and select the File tab.
From the tab opened in 1, press Upload and you can select fortune.py created on your PC, so upload it.
fortune.py
def get_fortune():
import random #Be careful because it is random, not randam
results = ['Daikichi', 'Kichi', '小Kichi', 'Bad', '大Bad', '末Kichi']
return random.choice(results)
import fortune
result = fortune.get_fortune()
print("What's today's fortune. .. ..", result)
** A library is a file that can be used by reading a certain amount of versatile processing (functions, classes, etc.) from another program. ** ** In Python, what can be basically imported is called a library. In addition, library is a general name, and in Python, if there is a notation of library basically, please think of it as a module explained below.
** A module is a file that summarizes Python code, and a file that can be reused by other programs is called a "module". ** ** It doesn't work by itself, but you can use the module by importing it. ** A package is a collection of \ _ \ _ init \ _ \ _. Py and multiple modules in a directory. ** ** \ _ \ _ Init \ _ \ _. Py is placed in the package directory and will be executed when you import the package.
The simple usage of the import statement is as follows. ** import Module you want to load ** The part of the module you want to load is the filename of another Python file with the .py extension removed. For example, if you want to load the sys module, do the following: (The sys module is one of the modules that can be used when Python is installed. This is called the ** standard module **, and there are many other modules such as the os module.)
import sys
When importing multiple modules, you can separate the module names with ",".
import sys, os
For example, if you want to use the cos function of the math module, you can use it with ** module name.function name (argument) **.
import math
math.cos(1) # 0.5403023058681398
This time we will make a fortune program (fortune-telling module). First, create the main program. (The file name is free, but here it is main.py.)
main.py
import fortune
result = fortune.get_fortune()
print("What's today's fortune... ", result)
Next, let's create a fortune module. Save the following program with the file name ** fortune.py ** in the same location as the main program (main.py) created above.
fortune.py
def get_fortune():
import random #Be careful because it is random, not randam
results = ['Daikichi', 'Kichi', '小Kichi', 'Bad', '大Bad', '末Kichi']
return random.choice(results)
Now, I think that main.py and fortune.py are saved in the same folder, so let's execute the created main.py. To run it, run the saved main.py from the terminal if you are using a Mac or from the command prompt if you are using Windows.
python
python main.py
** When executing the above, if you start the terminal as it is and execute the above command, the error (null): can't open file'main.py': [Errno 2] No such file or directory May appear. ** ** This is because the file main.py does not exist in the current hierarchy.
If the output result changes every time you execute it, it is working without any problem.
from file name (module name) import \ * allows calling without specifying a file name.
from module name import*
When using a module function, etc., if you want to omit the description of the module name and use only the function name, use the following.
from module name import function name,Function name, ...
Based on the above syntax, you can write the program as follows.
from math import cos, sin, tan
cos(1)
Earlier, I wrote random.choice (results) in fortune.py, fortune.py can be rewritten as follows using from.
def get_fortune():
from random import choice
results = ['Daikichi', 'Kichi', '小Kichi', 'Bad', '大Bad', '末Kichi']
return choice(results)
Also, if you want to import all the members (functions, constants, classes, etc.) in the module without specifying a name, specify as follows.
#from module name import*
from math import *
cos(1)
sin(1)
It is in the function that random is imported in the sample in fortune.py, You can also import outside the function.
from random import *
def get_fortune():
results = ['Daikichi', 'Kichi', '小Kichi', 'Bad', '大Bad', '末Kichi']
return choice(results)
print(get_fortune())
sin(1)
# main.py
import fortune
result = fortune.get_fortune()
print("What's today's fortune... ", result)
It was described as import fortune, but you can give it an alias by using as. Below is a sample with an alias.
import fortune as ft
result = ft.get_fortune()
print("What's today's fortune... ", result)
You can now call ft.get_fortune () by giving it an alias.
I imported everything with *, but you can also import only the parts you need.
from fortune import get_fortune
result = get_fortune()
print("What's today's fortune... ", result)
It is also a sample that gives an alias and imports only get_fortune.
from fortune import get_fortune as gf
result = gf()
print("What's today's fortune... ", result)
** You can find the location of the library in the module's file or path attributes. ** ** For example, you can check it by doing the following.
import os
print( os.__file__ ) # /Users/aiacademy/anaconda3/lib/python3.6/os.py
Start the terminal for Mac and the command prompt for Windows, move the main.py created earlier to the folder where the next main.py is located, and execute it.
python main.py
When you run
What's today's fortune...It is ○○.
As you can see, in ○○, you can see that the result of fortune changes randomly for each execution. If you cannot run the Omikuji app in this chapter, please refer to the text below. [Let's make an Omikuji app that works at the command prompt! ](? Id = 193)
Python is called an object-oriented language. This chapter describes the basics of ** "classes" **, which are essential for understanding this object-oriented language. You can use classes not only in Python but also in object-oriented languages. ** Object orientation is hard to understand, so You don't have to try to understand everything with this text alone, you just need to understand what it is, so keep learning at your own pace. ** **
This time around, the following ** 10 important terms ** will appear in this chapter. All of these are available not only in Python but also in object-oriented languages (Java, etc.). If you don't understand the meaning of a term, go back to the section that explains it one by one and review it.
** 1. Object-oriented ** ** 2. Class ** ** 3. Object ** ** 4. Constructor ** ** 5. Instance ** ** 6. Method ** ** 7. Inheritance ** ** 8. Multiple inheritance ** ** 9. Override ** ** 10. Parent and child classes **
** Object-oriented is a programming style / method **, which is one of the programming paradigms. In addition to object-oriented (object-oriented programming), the programming paradigm includes functional programming and ** procedural programming **. In procedural programming, you write a series of procedures, flow from top to bottom, and write code while changing the state of variables and so on. For example, the procedural type is as follows.
a = 10
b = 20
y = a + b
print(y) # 20
However, ** Procedural programming has various problems as the number of programs increases because all the code is [global variables](? Id = 6 & section = functional% 20 variable scope). ** ** For example, change a global variable in one function and overwrite it in another function. This makes it increasingly difficult to manage programs in ** procedural programming. ** ** Object-oriented programming has emerged as an opportunity to solve that problem. ** Object orientation not only solves the above problems, but also improves development efficiency and maintainability. ** ** Programming languages that can take advantage of object orientation include languages such as Python, Java, and C ++. This time, I will start with the basic object-oriented classes using Python.
I've seen data types such as int and str before, but ** classes are a mechanism for creating data structures **, and you can use ** classes to create new data types. ** ** Classes are often described as ** design documents that create objects **. It is an image diagram of the relationship between a class and an instance.
** Create an instance (object) by class (design drawing with a mechanism to create a data structure) → instantiation (baking takoyaki).
** Instantiation is to create an instance (object) from a class. ** ** We will discuss objects in the next section.
Now let's actually create a class.
#When creating a class, make sure to create the class name in CamelCase "Format to connect with capital letters of words".
#Also, for functions and methods that appear in this chapter, the snake case(Use a format that connects lowercase words with an underscore).
#(As an aside, a case with only lowercase letters and no underscore is called a lower case.)
#Create a Sample class. (The file name to save can be any name.)
class SampleClass: #Uppercase the first letter of the class name and uppercase the first letter of multiple words
#Please open 4 spaces in the class and indent. You can define variables and methods (functions in the class are methods) in the class.
'''sample class '''
sample = SampleClass() #To use an instance class, like a function call, the class name()Instantiate by doing. This way you can use the class. An instance of SampleClass is stored in sample. This data created from the class is called an instance.
sample.name = "A"
sample2 = SampleClass() #You can create as many data as you like from this Sample type, so let's create sample2.
sample2.name = "B" #Various attributes can be created for sample2.
print(sample.name) #The name of sample is A
print(sample2.name) #The name of sample2 is B
To create an empty class (empty class), write:
class SampleClass:
pass #Empty class by using pass(And functions)Can be made.
sample = SampleClass()
sample.name = "Sample"
** An object is one that has data (attributes) and methods (functions defined in a class). ** ** And all Python values are objects, and the objects define functions (methods) that can be executed.
** The constructor is used to initialize the instance of the target class. ** **
You can write a special method in your class called ** \ _ \ _ init \ _ \ _ **. ** This is the initialization method, called the constructor, which is called only once when the class is instantiated. ** ** Also, the data contained in the ** class is called an attribute **.
Let's actually look at the program. (This time, we will create the User class.)
class User:
def __init__(self, name): #Defines a variable that receives the value that is instantiated and passed
#Instance variable (attribute initialization)
self.name = name
print("The constructor was called")
def hello(self):
print("Hello " + self.name)
user = User("Sample User") #I am creating an instance called user.
The constructor of the User class takes an argument called name and initializes the variable self.name (this variable is called an instance variable) with that argument. Instance variables are variables that are stored in individual instances. Here name is an instance variable. In the hello method, the attribute name is written after self, but by writing it like this, you can create and access instance variables.
user = User("Sample User")
py = User("python")
user.hello()
py.hello()
** A method is a function defined in a class. ** ** Last time, I defined an empty SampleClass, but this time I will create a SampleClass that has a method.
class SampleClass:
#Method Be sure to attach the first argument self to the method. self refers to the instance of the class itself
def set_name(self, name):
self.name = name #You need to store the received value in an instance of SampleClasas. For that self.name =Let's call it name. Since self itself refers to an instance of SampleClass, prepare an instance variable called name and assign the argument name.
def hello(self):
print("hello, {0}".format(self.name))
sample = SampleClass()
sample2 = SampleClass()
sample.set_name("Python") #Since self indicates itself, there is no problem with just the Python argument that corresponds to name.
sample2.set_name("AI")
sample.hello()
sample2.hello()
** Inheritance is a mechanism to create a new class based on an existing class. ** ** By using inheritance, it is possible to efficiently extend existing classes and improve the maintainability of programs. User (parent class, superclass, base class)-> SuperUser (child class, subclass, derived class) The child class SuperUser class that we are going to define has the functions of the parent class, so when defining the child class, we only need to define the new functions that we want to add. By inheriting, you can reuse an existing class and create a new class. Let's actually see it.
class User:
def __init__(self, name):
self.name = name
def hello(self):
print("Hello " + self.name)
class SuperUser(User): #To inherit a user class()If you write the User class inside, it is oK.
def __init__(self, name, age):
# super()You can call the methods of the parent class by using.
super().__init__(name) #Call the parent class constructor from this class
self.age = age
#Method override
def hello(self):
print("SuperHello" + self.name)
#Also, in the method of this class, for example, overridden
#In the method, super()You can also call the methods of the parent class User by using.
super().hello()
t = SuperUser("tani", 100)
t.hello()
** Multiple inheritance is inheritance from multiple parent classes. ** ** In the example below, it means that Base1 and Base2 are inherited from the parent class (base class).
#Python supports multiple inheritance.
#A class definition with multiple base classes has the following syntax:
class SampleClassName(Base1, Base2):
・ ・ ・ ・
・ ・ ・ ・
#Inherit Base2 after inheriting Base1 above.
** Overriding a method with its own functionality is called overriding. ** ** The sample method in the Derived class below is overridden by overriding the sample method in the Base class. I overridden only the sample method this time, but you can override any method including \ _ \ _ init () \ _ \ _.
#Base class
class Base:
def sample(self):
print("Base.sample()Was called")
def test(self):
print("Base class test method was called")
#Derived class
class Derived(Base):
def sample(self): #Override the sample method of the Base class
print("Derived.sample()Was called")
self.test() #Call the test method of the Base class
d = Derived()
d.sample()
The original Base class is called ** parent class or superclass (or base class) **. The new Derived classes are called child classes, subclasses, derived classes, and so on.
In this article, you learned what Python is, what you can do with Python, variables and data types, if and for statements, modules and classes, and more. All of them are basic contents, so let's hold them firmly.
Recommended Posts