Memo # 1 for Python beginners to read "Detailed Python Grammar"

Introduction

I started to touch it because I wanted to study Python, so [Detailed explanation of Python grammar](https://www.amazon.co.jp/Python%E6%96%87%E6%B3%95%E8%A9%B3 % E8% A7% A3-% E7% 9F% B3% E6% 9C% AC-% E6% 95% A6% E5% A4% AB / dp / 4873116880 / ref = cm_cr_arp_d_pl_foot_top? Ie = UTF8) Make a note of what you thought. I usually write mainly in Java, so I think it will probably be the focus of what is different from Java.

Chapter 1 Introduction

--The name Python comes from "Monty Python's Flying Circus" (comedy show). --In the sample code, people like "foo", "bar", and "baz" have a habit of using "spam", "ham", and "egg". (It seems that it was used in Tale) ――I think that the unfamiliar word comes from this.

Chapter 2 Running Python

_Behavior


>>> 1+1
2
>>> _ #The last evaluated calculation result is "_Is it really?
2
>>> _ + _ # 2+2=
4
>>> _ # 「 _Is set to 4
4

Write multiple processes at once (do not do basic)


print(1+1); print('Hello')

--In python, specify the code block only by indentation. (Also called "suite") --The standard indentation is 4 spaces.

Numeric type


>>> 100 #integer
100
>>> 100.0 #Floating point number
100.0
>>> 0b100 #Binary number
4
>>> 0o100 #8 base
64
>>> 0x100 #Hexadecimal
256

Concatenation of conditional operators


>>> 99
99
>>> 0 < _ < 100  # (0 < _) and (_ < 100)You don't have to write like
True

Dictionary object


#So-called associative array / hash table. key& value
>>> {1:'one', 2:'two'}
{1: 'one', 2: 'two'}
>>> {} #Empty dictionary
{}

>>> d = {1:'one', 2:'two'}
>>> d[1] #Element reference
'one'
>>> d[1] = 'Ichi' #Change the value of an element
>>> d[1]
'Ichi'
>>> d
{1: 'Ichi', 2: 'two'}
>>> del d[1] #Delete element
>>> d[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 1
>>> d
{2: 'two'}

list


#The list can be updated, but it cannot be used as a dictionary key.
L = [1, 2, 3]
L = [] #Empty list
L = [1, 'Two', [3, 4, 5]]

Tuple


#Tuples cannot be updated, but can be used as dictionary keys.
t = (1, 2, 3)
t = 1, 2, 3  # ()Is not required
t = ()  #Empty tuples()Expressed in
t = (1, 'Two', [3, 4, 5])

Sequence access


#Arrays such as strings, lists, and tuples are called sequences, and any kind of object can access its elements in the same way.
>>> S = 'abcdefg'  #Even a string
>>> S[0]
'a'
>>> S[2]
'c'
>>> L = [0, 1, 2, 3, 4, 5]  #Even on the list
>>> L[0]
0
>>> L[2]
2

#Take from behind with a negative index value
>>> S[-1]
'g'
>>> S[-3]
'e'

#Specify the range and take
>>> S[1:4]
'bcd'
>>> S[-3:-1]
'ef'
>>> S[:3]  #If the start position is omitted, the same applies from the beginning and the end.
'abc'

#Change elements
>>> L = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> L[0] = 'spam'
>>> L
['spam', 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> L[0:4] = ['ham', 'egg']  #It seems that it can be updated by specifying the range, ignoring even the number of elements if it is a list
>>> L
['ham', 'egg', 4, 5, 6, 7, 8, 9]

if statement

--In Python's if statement, not only the logical value type True, but all non-zero numbers and non-empty collections are true. --Number 0, empty collection, None object is false.

for statement

--The Python for statement iterates through the __ string and each element in the collection. __

python


>>> S = 'spam'

#It seemed that the character string type was looped as it was, which made me feel uncomfortable, but if it is "execution of processing for each element"
#I'm convinced that "sequences can access elements in the same way for any kind of object"
#Strictly speaking, it is an "Iterable object" (described later).
>>> for c in S:
...     print(c)
... 
s
p
a
m

else clause


while runnning:
    if not c:
        break
else:
    #Execute when the while loop ends without breaking, the same for for

Iterable object

--The Python collection (list / dictionary. Data structure for efficiently manipulating objects such as set types) provides an interface (__ iterator __) for fetching element objects one by one. ing. --The object that implements the interface for getting the iterator is called Iterable object. --Since all lists and character strings are iterable objects, various language functions and libraries can be written in an element type-independent manner. (Example: for statement)

File objects are also iterable


import sys
for line in sys.stdin:  #Read line by line from standard input
    print(line, end='')  #Write the read line to standard output

function

function


>>> def avg(a, b, c):  #Function definition
...     return (a+b+c)/3
... 
>>> avg(10, 20, 30)
20.0
>>> avg(b=20, c=30, a=10)  #Argument can be called by name (keyword argument), avg(10, 20, 30)Same as
20.0

>>> def avg(a, b=20, c=30):  #You can also specify the default value of the argument
...     return (a+b+c)/3
... 
>>> avg(10)  # avg(10, 20, 30)Same as
20.0

class

class


>>> class Spam:  #Class definition
...     def ham(self, egg, bacon):  #Since the first argument always receives the object to which the method belongs, it is customarily set to self.
...         print('ham', egg, bacon)
... 
>>> obj = Spam()
>>> obj.ham('foo', 'bar')  # 'foo'Is the second argument,'bar'Is the third argument
ham foo bar

>>> class Spam2:
...     def __init__(self, ham, egg):  # __init__()The method is called automatically if it is in the class (like a constructor)
...         self.ham = ham
...         self.egg = egg
... 
>>> obj = Spam2('foo', 'bar')
>>> print(obj.ham, obj.egg)
foo bar

>>> obj.new_attribute = 1  #You can add attributes suddenly. Really?
>>> print(obj.new_attribute)
1

Recommended Posts

Memo # 4 for Python beginners to read "Detailed Python Grammar"
Memo # 3 for Python beginners to read "Detailed Python Grammar"
Memo # 1 for Python beginners to read "Detailed Python Grammar"
Memo # 2 for Python beginners to read "Detailed Python Grammar"
Memo # 7 for Python beginners to read "Detailed Python Grammar"
Memo # 6 for Python beginners to read "Detailed Python Grammar"
Memo # 5 for Python beginners to read "Detailed Python Grammar"
Basic Python grammar for beginners
~ Tips for beginners to Python ③ ~
Memo to ask for KPI with python
Beginners read "Introduction to TensorFlow 2.0 for Experts"
[Python] Read images with OpenCV (for beginners)
The fastest way for beginners to master Python
Python for super beginners Python for super beginners # Easy to get angry
python textbook for beginners
Try to calculate RPN in Python (for beginners)
Python basic grammar memo
Introduction to Programming (Python) TA Tendency for beginners
How to make Python faster for beginners [numpy]
[For beginners] How to study programming Private memo
OpenCV for Python beginners
[For beginners] How to use say command in python!
How to convert Python # type for Python super beginners: str
[For beginners] Learn basic Python grammar for free in 5 hours!
Python # How to check type and type for super beginners
Python memo (for myself): Array
Learning flow for Python beginners
Python Basic Grammar Memo (Part 1)
Python code memo for yourself
Python3 environment construction (for beginners)
3 Reasons Beginners to Start Python
Python basic grammar (miscellaneous) Memo (3)
Python #function 2 for super beginners
Python basic grammar (miscellaneous) Memo (2)
100 Pandas knocks for Python beginners
[Python] Sample code for Python grammar
Python for super beginners Python #functions 1
Python #list for super beginners
Python basic grammar (miscellaneous) Memo (4)
Introduction to Python For, While
Tips for Python beginners to use Scikit-image examples for themselves 4 Use GUI
[For beginners] How to read Numerai's HP + Submit + Convenient links
[R] [Python] Memo to read multiple csv files in multiple zip files
How to learn TensorFlow for liberal arts and Python beginners
Tips for coding short and easy to read in Python
How to convert Python # type for Python super beginners: int, float
[For beginners] Script within 10 lines (4. Connection from python to sqlite3)
Tips for Python beginners to use the Scikit-image example for themselves
[Python] Introduction to graph creation using coronavirus data [For beginners]
Python Exercise for Beginners # 2 [for Statement / While Statement]
Minimum grammar notes for writing Python
Python for super beginners Python # dictionary type 1 for super beginners
Python #index for super beginners, slices
<For beginners> python library <For machine learning>
Python #len function for super beginners
Beginners use Python for web scraping (1)
[Nanonets] How to post Memo [Python]
Run unittests in Python (for beginners)
Beginners use Python for web scraping (4) ―― 1
Python #Hello World for super beginners
Python for super beginners Python # dictionary type 2 for super beginners