First Python miscellaneous notes

For the first time in Python, make a note of what I looked up. Our experience languages are ActionScript3, C, C ++, C #, JS.

import

socket You will be able to handle communication. Communication processing by Python 17.2. Socket — Low-level network interface Man page of SOCKET

socket.socket() Creating a socket.

socket.setsockopt() Set socket options.

socket.SOL_SOCKET Socket level? For any socket, specify this for the time being

socket.SO_BROADCAST Broadcast settings.

socket.AF_INET IPv4 internet protocol

socket.SOCK_DGRAM Supports datagrams (connectionless, unreliable, fixed maximum length messages). Specify this for UDP communication.

random You will be able to handle random number functions. Generate a number (random value)

RPi.PGIO The sentence I found when I tried to L-Chika with RasPi. as is for naming an alias.

import RPi.GPIO as GPIO

How Python module import works L-Chika using Python's RPi.GPIO on Raspberry Pi

Indent required

This may be good.

print Output to the console. Is there a difference in the display of character strings between double quotes and single quotes?

print "bufferSize : " + size

If you try to output with a feeling like TypeError: cannot concatenate 'str' and 'int' objects "Don't mix the molds," he gets angry.

print "bufferSize : " + str(size)

It's OK if you cast it. Or

print "bufferSize : "
print size

Put out each. A little troublesome.

No semicolon required

You may put it in.

Checking the version in Terminal

$ python --version

Is it quite different between python 2 and 3?

No type specification required

It will be dynamically typed.

Assign to string

msg = "%s:%s" % (1, 100)  # 1:100

Python memo: When assigning a value to a string

Function def

You can define a function with a def statement.

def add(x,y):
    ans = x + y
    return ans

n = add(3, 5)
print n    # 8

Well, since indentation is compulsory, is it unnecessary to use curly braces?

Lists, tuples, dictionaries

--List -** [] ** (square brackets) --So-called array. --Tuple

Introduction to Python-Lists, Tuples, Dictionaries [Python] Review the basics (list, tuple, dictionary)

Null object is None

#↓ Correct answer
A is None
A is not None

#↓ Incorrect answer, seems to be slow
A == None

In Python, use is instead of == for None comparison Comparison of null objects in Python

elif Is else if written as elif in Python?

Japanese encoding

Even if you comment out in Japanese, you will get angry if you have characters other than ASCII, so if you specify the encoding at the beginning of the file, you will hear that it is also said in Japanese.

# coding=utf-8

Python and Japanese

in operator

Checks if the element contains the specified value.

list = ["A", "B", "C"]

print "B" in list        # True
print "D" in list        # False
print "B" not in list    # False
print "D" not in list    # True

Check element (in operator, index method, count method)

lambda Lambda expression. Anonymous function in Python.

def func(a, b):
    return a + b

print func(1, 2)    # 3

If you use lambda above,

print (lambda a, b: a + b)(1, 2)    # 3

And it can be stored in a variable. Hmm.

f = (lambda a, b: a + b)
print f(1, 2)    # 3

lambda expressions are very interesting

reduce function

Use when you want to combine multiple elements into one. Specifically, two elements are extracted from the beginning of the array and processed, and then the result and the next element are processed, and so on.

print reduce(lambda x, y: x + y, range(1, 5))    # 10

Import is required for Python3.

Comparison of how to use higher-order functions in Python 2 and 3

test.py is

I was completely doing this to try it for a moment Because there is a standard library called test. Don't make test.py in Python!

Catch [ctrl] + [c]

I was worried about the LED lighting from GPIO at the end of the Python program with RapPi, so I caught [ctrl] + [c] and wrote the end process.

try:
    while True:
        #Normal processing here
except KeyboardInterrupt:
    print("interrupted!")
    #End processing here

Catch Ctrl-C in Python

pass statement

do nothing. It is used when creating empty functions and classes. Is that so?

def func()
    pass

Introduction to Python-Control Syntax

Build a server

I was wondering what I could do when I said "Python is fun!", But the server starts up too easily.

$ python -m SimpleHTTPServer

Python can build a web server in just one line Creating a web application with Python (without Apache or web framework)

for statement

This is the first time I've written it.

for integer in object:
processing

If you put an array in the object, it will be executed in order.

list = [1,2,3]
for num in list:
    print(num) # 1 2 3

If you specify the range function for the object, it will be executed accordingly.

for num in range(5):
    print(num) # 0 1 2 3 4

It means that it starts from 0 and runs 5 times.

The behavior also changes depending on the number of arguments of the range function.

Explanation of python for statement for beginners! This is perfect for sentence basics

if statement

You write like this. Is Python basically trying to avoid writing parentheses in sentences as much as possible?

if conditional expression 1:
processing
elif conditional expression 2:
processing
else:
processing

Multiple conditional branches (if ... elif ... else)

Block comment out

Basically, it seems that you can only comment on lines with #. Quotation can play an alternative role. It can also be nested in singles and doubles.

"""
print "hello"
'''
print "heyhey"
'''
"""

Comment out

Object identification value

Every Python object has its own unique "identification value (ID)". So, there are ** immutable ** objects and ** mutable ** objects. A ** immutable ** object is an object whose ID changes at the same time when the value of the object changes. Ordinary integers or strings?

Objects that are ** mutable ** are objects with a fixed ID. Like List.

So, in the following state, Python seems to recognize that ** the object pointed to is the same because the ID does not change **. Hmm, remember.

a = [1,2,3,4,5]
#I made a list called b that copied the contents of the list called a(I'm going)
b = a

#Later a[2]Changed the value of(I'm going)
a[2] = 5
print(a) # [1, 2, 5, 4, 5]
print(b) # [1, 2, 5, 4, 5]

Be careful when handling Python lists

Multidimensional array

When trying to realize a multidimensional array in Python --Multiple list --NumPy array It seems that there are two. NumPy is static and fast, so let's use it here.

import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
print a
# [[1 2 3]
#  [4 5 6]]

Basics of NumPy array

class

class Spam:
    val = 100
    def ham(self):
        self.egg('call method')
    def egg(self, msg):
        print("{0}".format(msg))
        print(("{0}".format(self.val))

spam = Spam()
spam.ham()

# --- output ---
# call method
# 100

What the hell, * self *.

In Python methods have at least one argument. It is customary to always name this first argument self.

I see.

Python Basic Course (13 classes)

format function

Used to embed variables in strings.

'Arbitrary string{}Arbitrary string'.format(variable)

** Specify with argument **, can also be

apple = 50
orange = 100
total = apple + orange

print('Apple:{0}Yen mandarin orange:{1}Yen total:{2}Circle'.format(apple, orange, total))

# --- output ---
#Apples: 50 yen Mandarin oranges: 100 yen Total: 150 yen

[Introduction to Python] How to write a character string with the format function


When the return value of the function is multiple

If you get a tuple and call the element as it is, you can use the value. It's fresh because I've never written it like this.

def tasu(x):
    a = x + 1
    str = "data : "
    return (str, a)

(n, m) = tasu(1)
print n
print m

# --- output ---
# data :
# 2

How to return multiple return values in a function


"L" at the end of the number

RECVMSG           = 0x00000021L

When I looked at some sample code, I thought that there was an "L" after the hexadecimal number.

This is called a "long integer", which is the same as an integer, but there is no limit to the number of digits that can be handled. Even if the number of digits is exceeded without adding it, it will be converted to a major number without permission.

Hexadecimal numbers are treated as such by prefixing them with "0x" and octadecimal numbers with "0". When both are printed, they are output in decimal numbers.

Numeric literal


[Raspberry Pi] Speak

I put in OpenJTalk. [How to synthesize speech (Open JTalk)](http://www.raspberrypirulo.net/entry/2017/08/29/%E9%9F%B3%E5%A3%B0%E5%90%88%E6 % 88% 90% E3% 82% 92% E3% 81% 99% E3% 82% 8B% E6% 96% B9% E6% B3% 95% 28Open_JTalk% 29)

I also got kanji. It's a fairly natural utterance, but I may not use it because the sense of science fiction is not enough for the machine to speak.


Python fun! !! !! !! !!

Recommended Posts

First Python miscellaneous notes
Python scraping notes
First time python
Python study notes _000
First Python 3 ~ First comparison ~
Python learning notes
Python beginner notes
First time python
python C ++ notes
Python study notes _005
Python grammar notes
Python Library notes
First Python ~ Coding 2 ~
First python [O'REILLY]
python personal notes
python pandas notes
Python study notes_001
python learning notes
Python3.4 installation notes
missingintegers python personal notes
PyQ ~ Python First Steps ~
Python package development notes
[Python] Python / Scikit-learn's first SVM
Python ipaddress package notes
Python basic grammar (miscellaneous)
[Personal notes] Python, Django
Python Pickle format notes
[Python] pytest-mock Usage notes
Matlab => Python migration notes
Notes around Python3 assignments
Notes using Python subprocesses
[Python] Chapter 01-01 About Python (First Python)
Python try / except notes
Python framework bottle notes
Python notes using perl-ternary operator
Web scraping notes in python3
Python standard unittest usage notes
Python notes to forget soon
Python notes using perl-special variables
Python 處 處 regular expression Notes
Python Tkinter notes (for myself)
First neuron simulation with NEURON + Python
[Python] Notes on data analysis
go language learning miscellaneous notes 1
Python data analysis learning notes
Python basic grammar (miscellaneous) Memo (3)
Notes on installing Python on Mac
Python basic grammar (miscellaneous) Memo (2)
Get Evernote notes in Python
Python basic grammar (miscellaneous) Memo (4)
Notes on installing Python on CentOS
Miscellaneous notes that I tried using python for the matter
Notes on Python and dictionary types
First simple regression analysis in Python
Python
First Python 3 ~ The beginning of repetition ~
Minimum grammar notes for writing Python
Notes on using MeCab from Python
First Python 3 ~ Extra: Numerical Random Fantasy ~
[GUI with Python] PyQt5-The first step-
Prepare your first Python development environment