Python quick start

When I try to use it after a long time, I forget various things, so I wrote a memo like Bootcamp. Below is an example of how to use it on Ubuntu. In addition, it is Python 2 system, so I do not know.

Preparation

First, prepare tools for installing various Python libraries.

easy_install


$ sudo apt-get install python-setuptools

pip


$ sudo apt-get install python-pip

If you need the library, add it with the pip command. (Example: feedparser)

(Example)


$ sudo pip install feedparser

When via a proxy.

(Example)


$ sudo pip install feedparser --proxy proxy.yourdomain.xx:8080

Run

Executing the file that describes the script (eg my_python.py).

$ python my_python.py

Coding style

You can create common rules for projects, but the shortcut is to comply with PEP8.

There is also a Google Python Style Guide.

If you want to quickly remember how to use it, the contents of this page will do the trick, but if you want to start programming in earnest, it is better to read the above rules. (As with the notation, various techniques can be helpful)

Below are just the main points.

Indent

With 4 spaces. (Do not use tabs)

Blank

Do not put spaces inside parentheses, square brackets, or curly braces.

# Yes:
spam(ham[1], {eggs: 2}, [])
# No:
spam( ham[ 1 ], { eggs: 2 }, [ ] ) 

Do not put spaces before commas, semicolons, and colons. Insert a space after the comma, semicolon, or colon other than the end of the line.

# Yes:
if x == 4:
    print x, y
x, y = y, x
# No:
if x == 4 :
    print x , y
x , y = y , x

Do not put spaces before opening the arguments, the array, the parentheses that start the slice, and the square brackets.

# Yes:
spam(1)
dict['key'] = list[index]
# No:
spam (1)
dict ['key'] = list [index]

Term operators such as assignment (=), comparison (==, <,>,! =, <>, <=,> =, In, not in, is, is not), evaluation (and, or, not) Put spaces on both sides of. Whitespace on both sides of the arithmetic operator is personal judgment, but whitespace characters are inserted on both sides of the term operator.

# Yes:
x == 1
# No:
x<1

Do not put spaces on either side of the ‘=’ symbol for keyword values or initial values.

# Yes:
def complex(real, imag=0.0): return magic(r=real, i=imag)
# No:
def complex(real, imag = 0.0): return magic(r = real, i = imag)

Do not insert spaces to align consecutive lines vertically, as this will reduce maintainability. (:, #, =, etc.):

# Yes:
foo = 1000  # comment
long_name = 2  # comment that should not be aligned

dictionary = {
    "foo": 1,
    "long_name": 2,
    }
# No:
foo       = 1000  # comment
long_name = 2     # comment that should not be aligned

dictionary = {
    "foo"      : 1,
    "long_name": 2,

naming

type internal External
package lower_with_under
module lower_with_under _lower_with_under
class CapWords _CapWords
exception CapWords
function lower_with_under() _lower_with_under()
global/Class constant CAPS_WITH_UNDER _CAPS_WITH_UNDER
global/Class variables lower_with_under _lower_with_under
Instance variables lower_with_under _lower_with_under (protected) or __lower_with_under (private)
Method name lower_with_under() _lower_with_under() (protected) or __lower_with_under() (private)
function/Method parameters lower_with_under
Local variables lower_with_under

coding

Hello World

print 'Hello World'

Handling of code blocks

Super basics of Python. Block by indent instead of {}.

Styles such as C


if (cond) {
    ...
}
else {
    ...
}

Python style


if cond:
    ...
else:
    ...

print statement format

Format output using % d and% s is possible.

ans = 100
print 'answer is %d' % ans

When handling multiple variables, enclose them in ()

count = 1
line = 'hogehoge'
print '%d: %s' % (count, line)

Handling of line breaks in print statements

The print statement is automatically broken even if you do not add \ n at the end.

print 'My name is '
print 'John' #Output with line breaks

To prevent line breaks, add , to the end of the character literal. Attach it outside the literal, not inside it.

print 'My name is ',  # ,Put on
print 'John' # My name is John.

Comment text

The comment text is after #

# comment!

var = 10 # initial value

There is no comment-out notation that spans multiple lines. It can be replaced by using the string notation '''. (These descriptions are invalidated at compile time)

'''
xxxx
'''
class MyClass:
    pass

Line breaks in the middle

Unlike Java etc., ; at the end of the line is unnecessary. Instead, you can't easily break a line in a line.

NG


# NG
msg = 'I am not in Japan now.'
    + 'But I have been there.'

You can start a new line in the middle by adding \ at the end of the line.

OK


# OK
msg = 'I am not in Japan now.' \
    + 'But I have been there.'

Line breaks can be made in the text enclosed by () or []. Also, the indentation after the line break may be free.

OK


my_method('My', 'Name',
    'Is', 'Mike', 'Davis', '.')

def func():
    v = [1, 2, 3,
4, 5, 6] #Grammatically OK,Avoid it because it is hard to see.

variable

No need to specify the type in the variable declaration. Numerical values, strings, and arrays are all objects.

val = 10
msg = 'foo'
ary = [1, 2, 3]
c = MyClass()

Array definition

A form that is often seen in other languages. A line break may be inserted between the elements.

list = [
     "Ichiro",
     "Jiro",
     "Saburo"]

Logical operation

You cannot use | or &. Use ʻand and ʻor instead.

if a == 1 and b == 2:
    # do something

Handling of Boolean

Use True, False.

if True:
    print "Always True"

Handling of null

Use None instead of null.

if value is None:
    # do something

Ternary operator

Note that the notation is different from Java.

data = 100
value = 'even' if data % == 0 else 'odd'

Function definition

Use def. In python, functions are also objects.

def func(value):
     return value*2

How to write main process

Writing as follows makes the main process easier to understand.

def main():
    # do something
    ...

if __name__ == "__main__":
    main()

Handle run-time parameters

Use the sys module. ʻArgvs [0]` is the script name.

import sys

argvs = sys.argv
argc = len(argvs)
if (argc != 2):
     print 'Usage: %s <file>' % argvs[0]
     quit()

print 'param: %s' % argvs[1]

is and ==

ʻIsis identity (== in Java) ==` is equality (equals () in Java) Also, unlike Java, all numbers are objects.

That number is a bit confusing to understand.

a = 1
b = 1
if a is b:
    print "a is b"
if a == b:
    print "a == b"

Intuitively, "a == b" shouldn't be "a is b", When the above is executed, "a is b" is also output.

"a is b"
"a == b"

This seems to be due to the reuse of immutable data and the cache. By the way, probably because the compiler is smart, it will be "a is b" even in the following cases. (Of course a == b)

a = 1 + 3
b = 2 + 2
if a is b:
    print "a is b"

In the case of a character string, True is returned with ʻis when it is reused like a numerical value. However, note that ʻis may be False if it is dynamically generated.

x = "X"

a = "XY"
b = x + "Y"

if a == b:
    print "a == b"
if a is b:
    print "a is b"

output


a == b

By the way, you can get the address of the object by using the ʻid () function. Use it for debugging purposes when ʻis behaves differently than expected.

a = "foo"
print "a at 0x%x" % id(a)

if-else syntax

I often forget this, but I use ʻelif`.

if i % 15 == 0:
    print 'FizzBuzz'
elif i % 3 == 0:
    print 'Fizz'
elif i % 5 == 0:
    print 'Buzz'
else:
    print i

for / while statement

It is convenient to use range (). The second argument of range () is the maximum value, but this value is ** not included **.

for i in range(0, 5):
    print 'id = %d' % i

output


id = 0
id = 1
id = 2
id = 3
id = 4

When starting from the middle.

for i in range(2, 3):
    print 'id = %d' % i

output


id = 2

You can specify step with the third argument. In this case as well, the maximum value of the second argument is not exceeded.

for i in range(0, 10, 2):
    print 'id = %d' % i

output


id = 0
id = 2
id = 4
id = 6
id = 8

You can also specify an array.

for i in [0, 2, 3]:
    print 'id = %d' % i
for c in ['red', 'green', 'blue']:
    print 'color = %s' % c

You can also specify a subarray.

colors = ['red', 'green', 'blue']
for c in colors[1:]:
    print 'color = %s' % c

output


color = green
color = blue

There is a syntax for-else. The else clause is executed when the for loop processing is completed.

for i in range(0, 3):
    print 'i = %d' % i
else:
    print 'done'

output


i = 0
i = 1
i = 2
done

If you break in the middle, the else clause will not be executed.

for i in range(0, 3):
    print 'i = %d' % i
    if i == 1:
        break
else:
    print 'done' #Not executed

while statement. You can also use the else clause here.

i = 5
while 0 < i:
    print 'id = %d' % i
    i -= 1
else:
    print 'done'

Character literals including line breaks (here document style)

Enclose in '''.

val = '''this is a pen.
but it's not my favorite color.
I love red.
'''

If you want to indent and write in the code, there are the following description methods.

import textwrap

print textwrap.dedent('''\
AIUEO
Kakikukeko
SA Shi Su Se So''')

try-except syntax

You can handle exceptions with the try-except-finally syntax, similar to Java's try-catch-finally syntax. Also, in Python, the else clause can be specified, and it is executed when the process is completed without the occurrence of an exception in try.

try:
    val = int("123") # no exception
    print 'val = %d' % val
except ValueError:
    raise
else:
    print '>> else'
finally:
    print '>> finally'

In this case, Error / Exception does not occur in the try clause, so the output is as follows.

output


val = 123
>> else
>> finally

Dare to generate an Error in the try clause.

try:
    val = int("abc") # ValueError
    print 'val = %d' % val
except ValueError:
    # raise
    pass
else:
    print '>> else'
finally:
    print '>> finally'

In this case, the output will be:

output


>> finally

In addition, supplementary Errors and Exceptions can be specified collectively with ().

try:
   ...
except (XXXError, YYYError, ZZZException):
   ...

Simple class definition

It can be defined as follows. Member variables do not have to be declared one by one. The first argument self is always required and does not need to be specified when calling.

class ClassName:
    def __init__(self, arg1, arg2):
        self.member1 = arg1
        self.member2 = arg2

    def method(self, param1):
        // logic  

Instantiation-> Call.

data = ClassName('nameA', 'nameB')
data.method('param1')

Convert to string

In the following example, print is not possible.

val = 120
print "val + " val

It can be explicitly converted to a string with str ().

printt "hoge=" + str(123)

Convert to integer

Convert a string to an integer.

val = int("23")

If conversion is not possible, ValueError occurs.

try:
    v = int("abc")
except ValueError:
    print 'ValueError occurs'

Convert Hex string to decimal int

Specify the second argument of int ()

value10 = int ('0xF6', 16)

System command execution

For portability, don't use it.

import os
os.system('<command>')

(Example)


os.system('grep TvC -R .')

Receive the result of a system command

You can receive the result of the system command as a character string. When there is no result, it seems that an empty string is returned instead of None.

This is also portable and will not be used extensively.

import commands
r = commands.getoutput('<command>')

(Example)


r = commands.getoutput('date')

Unsupported notation

switch statement

You can use if --elif.

Increment operator

Numeric types can also be objects (immutable) and cannot be written as ʻi ++or--i. Use ʻi + = 1 and so on.

Recommended Posts

Python quick start
Start python
Python --Quick start of logging
Start using Python
[Python] Start studying
Python
Start to Selenium using python
[Gimp] Start scripting in Python
Start / stop GCE from python
3 Reasons Beginners to Start Python
Working with Azure CosmosDB from Python (quick start digging)
python datetime format quick reference table
Python3 compatible memo of "python start book"
kafka python
Python basics ⑤
python + lottery 6
Python Summary
Built-in python
Python technique
Studying python
Python 2.7 Countdown
Python memorandum
python tips
Start scraping
python function ①
Python basics
Python memo
ufo-> python (3)
install python
Python Singleton
Python basics ④
Python Memorandum 2
python memo
Python Jinja2
Apache Spark Document Japanese Translation --Quick Start
Python increment
atCoder 173 Python
[Python] function
Python installation
python tips
Installing Python 3.4.3.
Try python
Start / end match in python regular expression
Python iterative
Python algorithm
Python2 + word2vec
[Python] Variables
Python functions
Python sys.intern ()
Python tutorial
Python decimals
python underscore
Python summary
[Python] Sort
Note: Python
Python basics ③
python log
Python basics
[Scraping] Python scraping
Python update (2.6-> 2.7)
python memo