Even beginners want to say "I fully understand Python"

My child "Ogyaaogyaa !! Don't understand Python at all !!"

I said, "Oh, my child, who is a beginner in Python, doesn't understand Python and I don't have it today ..."

I said, "Everyone can't program Python quickly and easily, but I don't think that the super convenient functions that are so popular are not known. Moreover, when I try to use the convenient functions, I don't understand the meaning. I don't know. "

I said, "So this time, I'll introduce a grammar that is relatively new but doesn't seem to be well known! Everyone seems to be aiming for a complete understanding of Python!"

table of contents

-[Type hint](# type hint)

Type hint

I said, "At first, the type hints added in version 3.5!"

I "Do you all know that Python is a ** dynamically typed ** language?"

I said, "** Dynamic typing ** means that it will be automatically determined even if you don't specify the type!"

I said, "For example, in the ** statically typed ** language, variables are declared like this."

var name str = "nokonoko" //str type
var age int = 5 //int type

I "I wonder if I should decide in advance what value will be entered in the variable. If I enter a type other than the specified one, an error will occur."

I "On the other hand, Python ..."

name = "nokonoko" #str type
age = 5 #int type

I said, "Even if you don't bother to declare the type name like this, you can just declare the variable normally and decide the type without permission! Python is convenient!"

I said, "If you look at this, ** static typing ** is just annoying ..." But why is there still a statically typed language (rather, static typing is more popular ...?) ... because it has merit. Maybe it's roughly this much. "

--Speed: The operation is fast because the type determination has already been completed on the code. --Safety: The presence of the type reduces the probability of a seemingly unknown bug occurring. --Easy to read: It's hard to write, but it's easy to guess the behavior because the types of arguments and return values are self-explanatory.

I said, "** Small scale **, if you move it for the time being, it's OK **, ** speed doesn't matter **, ** if you develop by yourself **, you don't care about the type, but usually it does. It's not. "

I said, "It seems that Python was born to write simple scripts in the first place, but from such a popular situation, it seems that there was a strong request for Python to be statically typed. Because it's difficult to do ... I was born with a ** type hint **! "

I said, "It's used like this."

def hello(name: str) -> str:
    return f"Hello {name}"

I said, "You can set the type of variables and function arguments / return values! Now when you write code using IDE etc., you will be warned when you take a variable of different type as an argument. so!!"

I said, "But it's not really a typed language, it can be executed, so be careful!"

Summary

--Python is a dynamically typed language, so the type is automatically determined. --Type hints allow you to specify types for variables and functions --However, it is just a type ** hint ** and can be executed without causing a compile error.

Reference: typing --- support for type hints

Docstring

I said, "Next is Docstring! This is also a useful function! Let's see what it is!"

def hello(name):
    """Say hello to the person you put in the argument"""
    return f"Hello {name}"

I said, "You can embed a document in your code by putting a string enclosed in three quotation marks in a function (or a class module) like this!"

I said, "This is what makes it different from just a comment, but the string embedded here is not stored in the object's special method __doc__. "

I said, "That's what you can do withhelp ()in interactive mode to see the documentation, or Sphinx. If you use, it will automatically create a document and you will get a lot of deals! It's a bit different from just a comment. "

>>> help(hello)
Help on function hello in module __main__:
hello(name)
Say hello to the person you put in the argument

I said, "More !!!!!! By embedding multiple lines of Docstring, you can write the type hints I explained earlier in Docstring!"

I "like this!"

def hello(name):
    """Say hello to the person you put in the argument

    Args:
        name(str):The name of the person you want to say hello to

    Returns:
        str:Greetings
    """
    return f"Hello {name}"

I said, "You can check the type with IDE etc. just like you put the type hint with this!"

I said, "The one I wrote above is calledGoogle style, but I can write various things other than the arguments and return values, and there are other ways to write it in the first place, so if you're curious, check it out! "

I said, "It's convenient for developing with a large number of people, so everyone should try it!"

Summary

--By embedding a string enclosed in three quotation marks in a function, class, or module, the string is stored in the special method __doc__. --You will be able to use useful functions such as help () and reference in the IDE that will speed up development. --Type hints can be added by writing multiple lines

Reference: PEP 257 --Docstring Conventions

f-string

I "Next is the f-string (f string and!) Added in version 3.6"

I said, "There are about two ways to embed variables in a character string.

>>> name = "nokonoko"
>>> age = 5
>>> print("{}Is{}I'm old".format(name, age))
nokonoko is 5 years old

I "toka"

>>> print("%s is%s years old" % (name, age))
nokonoko is 5 years old

I "Tokayana."

I said, "That way ... it's old."

I "I can't do it like this now!"

>>> print(f"{name}Is{age}I'm old")
nokonoko is 5 years old

I said, "Doya. I've erased all the methods and symbols I don't understand and made it simpler!"

I said, "More. You can do this from Python 3.8."

>>> print(f"name={name}, age={age}") # 3.Up to 7
name=nokonoko, age=5

>>> print(f"{name=}, {age=}") # 3.From 8
name='nokonoko', age=5

I said, "By putting variables and = in {}, the variable names are automatically displayed! It's useful when debugging! "

I said, "Let's use this positively when creating a new project from convenience!"

Summary

--There are different types of string embedding, but the most convenient is the latest ** f-string **. --Since Python 3.8, you can also embed variable names, which is even more convenient.

Reference: 2.4.3. Formatted string literals

Walrus operator

I "Next is the ** walrus operator ** added in version 3.8!"

I said, "The walrus operator is the assignment operator: = , and it seems that it came to be called because it looks like a walrus's eyes and fangs when viewed from the side!"

I "... well, I can't see it !!!"

I said, "A function that allows you to leave it for the time being and assign it to a variable in an if statement or for statement! It's like this!"

# 3.Up to 7
>>> name = "nokonoko"
>>> if name == "nokonoko":
...     print("handsome, eh")
... else:
...     print("It's not handsome")
handsome, eh

# 3.From 8
if name := "nokonoko" == "nokonoko":
...     print("handsome, eh")
... else:
...     print("It's not handsome")
handsome, eh

I said, "Well, it's a natural result."

I said, "It's a function that allows you to assign to variables in conditional expressions like this, and it's an excellent one that can shorten redundant expressions."

I said, "However, this is not so well known because of its really new features, and depending on how it is used, it may reduce readability, so use it with caution!"

I said, "Especially in Python, ** if statements and for statements do not create a local scope **, so be careful!"

Summary

-** Walrus operator ** is an operator that can be assigned even in conditional expressions --Be careful about readability when using

Reference: PEP 572 --Assignment Expressions

Comprehension notation

I "Next is the inclusion notation!"

I said, "This is a function to simply create an object (having a reference to another object) that stores multiple values such as a variable called ** container object **."

I said, "The most commonly used list comprehension is."

List comprehension

#Create a new list
>>> numbers = []
>>> for i in range(10):
...     numbers.append(i)
>>> numbers
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

#If you use the comprehension notation, it will be like this
>>> numbers = [i for i in range(10)]
>>> numbers
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

I said, "It's an excellent thing that makes it possible to define an array using a for statement in one line!"

I said, "And you can also embed an if statement!"

#Ordinary for statement
>>> numbers = []
>>> for i in range(10):
...     if i % 2 == 0:
...         numbers.append(i)
...         
>>> numbers
[0, 2, 4, 6, 8]

#Comprehension notation
>>> numbers = [i for i in range(10) if i % 2 == 0]
>>> numbers
[0, 2, 4, 6, 8]

I said, "Furthermore, unlike the for statement, it closes the scope!"

#Ordinary for statement
>>> numbers = []
>>> for i in range(10):
...     numbers.append(i)
#The variable i defined in the for statement can be referenced.
>>> i
9

#Comprehension notation
>>> numbers = [i for i in range(10)]
#Exception occurs as variable i is undefined
>>> i
Traceback (most recent call last):
  File "<input>", line 1, in <module>
NameError: name 'i' is not defined

I said, "Because it prevents bugs, use inclusion notation as much as possible when creating a new list!"

I said, "By the way, the comprehension can't be used for anything other than lists! I'll introduce that too!"

Dictionary comprehension

>>> dict_obj = {str(i): i for i in range(10)}
>>> dict_obj
{'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}

Set comprehension

>>> set_obj = {i for i in range(10)}
>>> set_obj
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

Generator type

I said, "From the flow so far, I wonder if the tuple inclusion notation can be completed by changing the enclosing symbol to(), but this is a little exception, and a generator can be created. Be careful because it is complicated!"

gen_obj = (i for i in range(10))
gen_obj
<generator object <genexpr> at 0x10df04580>

I said, "There are various inclusion notations, and all of them are convenient, so please use them!"

Summary

--Comprehension is a function to simply create a container object. --Since the scope is closed, it is difficult to create bugs. --You can also create container objects other than lists --Deep nesting reduces readability, so be careful

Reference: 5. Data Structures

generator

I said, "Next is a generator! This is a function that has been around for a long time, but it's a function that beginners don't really understand how to use. If you don't bother to make a generator, you can make a list ..."

I thought, "I thought, but I feel like I'll be a big success in the following two points."

--When you want to make an infinite loop without stopping the process --When you want to handle a large amount of text data

I "for example ..."

while True:
    print("Returns a value")

I said, "When I write code, I immediately enter an infinite loop. It's possible that the system will continue to be consumed and the system will go down ... so I'm usually careful not to do it."

I said, "The same thing may happen even if you are limited to an infinite loop, or if you make a huge list with heavy mathematical calculations."

I said, "But if you use the generator as below, you don't have to squeeze the memory from creating a new element until the next element is required (calling the special method __next__)! "

I said, "There are two ways to create a generator, specifically this way!"

#How to create a function
>>> def my_gen():
...     x = 0
...     while True:
...         yield x
...         x += 1
#The return value is generator
>>> my_gen()
<generator object my_gen at 0x10df04510>

>>> for i in my_gen():
...     print(i)
0
1
2
3
...

#How to use a generator formula
>>> my_gen = (i for i in range(10000) if i % 2 == 0)
>>> for i in my_gen:
...     print(i)   
0
2
4
6
8

I said, "The return value of the generator is an iterator, so it can be used in a for statement!"

I said, "It seems to be very convenient when you want to read and process csv with 1 million records!"

I said, "By the way, the generator can also be converted to other container objects! But be careful as it can consume a lot of memory when it is created!"

>>> my_gen = (i for i in range(10000) if i % 2 == 0)
>>> my_list = list(my_gen)
>>> type(my_list)
<class 'list'>
>>> my_list
[0, 2, 4, 6, 8, 10, 12, 14, 16,...9992, 9994, 9996, 9998]

Summary

--The generator is an iterator that generates a value each time it is called --Not all values are expanded, so memory consumption can be reduced. --Convenient when handling large volumes of data

General comment

I said, "How did you do it! You got closer to a Python complete understanding man!"

My child "Ogyaaogyaa !! Python seems super easy !!"

I said, "Yeah. It seems that my child could understand Python completely. You in front of the screen will do your best to become a Python complete understanding man!"

Oshimai

Recommended Posts

Even beginners want to say "I fully understand Python"
Even in JavaScript, I want to see Python `range ()`!
I want to fully understand the basics of Bokeh
I want to understand systemd roughly
I want to debug with Python
I want to use jar from python
I want to build a Python environment
I want to analyze logs with Python
I want to play with aws with python
[Python] Pandas to fully understand in 10 minutes
[Introduction] I want to make a Mastodon Bot with Python! 【Beginners】
I want CAPTCHA to say HIWAI words
I want to do Dunnett's test in Python
I want to use MATLAB feval with python
I want to memoize including Python keyword arguments
I want to create a window in Python
I want to email from Gmail using Python.
[Python] I want to manage 7DaysToDie from Discord! 1/3
I want to mock datetime.datetime.now () even with pytest!
I want to make a game with Python
I want to merge nested dicts in Python
I want to use Temporary Directory with Python2
I want to use ceres solver from python
#Unresolved I want to compile gobject-introspection with Python3
I want to solve APG4b with Python (Chapter 2)
I want to sell Mercari by scraping python
[Python] I want to manage 7DaysToDie from Discord! 2/3
I want to make C ++ code from Python code!
I want to write to a file with Python
I want to display the progress in Python!
I want to write in Python! (1) Code format check
I want to understand (engineering) UMAP stronger than t-SNE
[For beginners] How to use say command in python!
I want to embed a variable in a Python string
I want to easily implement a timeout in python
I want to iterate a Python generator many times
Python that I would like to recommend to programming beginners
I want to generate a UUID quickly (memorandum) ~ Python ~
I want to handle optimization with python and cplex
[Python] I want to merge Excel files anyway (pandas.merge)
I want to write in Python! (2) Let's write a test
I want to randomly sample a file in Python
I want to inherit to the back with python dataclass
I want to work with a robot in python.
[Python3] I want to generate harassment names from Japanese!
[Python] I want to make a nested list a tuple
I want to write in Python! (3) Utilize the mock
I want to AWS Lambda with Python on Mac!
[ML Ops] I want to do multi-project with Python
I want to say that there is data preprocessing ~
I want to use the R dataset in python
I want to run a quantum computer with Python
I want to do something in Python when I finish
I want to manipulate strings in Kotlin like Python!
I want to do Wake On LAN fully automatically
Try to understand Python self
I want to solve Sudoku (Sudoku)
3 Reasons Beginners to Start Python
I understand Python in Japanese!
~ Tips for beginners to Python ③ ~
I want to be able to analyze data with Python (Part 3)