I tried an introduction to Python for dot installation, so it's a study record!
--Basic Python practices
--Variables and data types
--Numerical value
--String
--String operation commands
--Mutual conversion between numbers and strings
--List
--Tuple
--Set
--Dictionary
--Incorporate data into strings
--Conditional branching with ʻifstatement --Loop processing --Function --Variable scope and
pass`
coding: UTF-8
hello.py
#comment
print "hello, world!"
If you put Japanese in the code without defining it, it will be like this
$ python hello.py
File "hello.py", line 1
SyntaxError: Non-ASCII character '\xe3' in file hello.py on line 1, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
hello.py
# coding: UTF-8
#comment
print "hello, world!"
If you have defined it, you can put Japanese in the code.
$ python hello.py
hello, world!
--See Python Code Style Guide
--You can use ;
to separate sentences, but it is not recommended.
--The extension is .py
--Comment is #
--Strict indentation
--Label attached to data --Case sensitive
--Numerical value --String --Authenticity value --List (array) --Tuple --Dictionary (associative array, hash)
--Integer --Decimal --Complex number
item | operator |
---|---|
addition | + |
subtraction | - |
multiplication | * |
division | / |
quotient | // |
remainder | % |
Exponentiation | ** |
--When you operate an integer and a decimal, the result is always a decimal. --Division between integers is a truncated integer
u" Hello "
does not and dealing with a string of such len
instruction as is not working properly>>> print len("Hello")
15
>>> print len(u"Hello")
5
>>> print "Hello " + "World!"
Hello World!
>>> print "Hello World! " * 3
Hello World! Hello World! Hello World!
Escape line breaks, tabs, single quotes
>>> print 'hello\n wo\trld\\ it\'s the end'
hello
wo rld\ it's the end
Displaying data with line breaks
>>> print """<html lang="ja">
... <body>
... </body>
... </html>"""
<html lang="ja">
<body>
</body>
</html>
>>> a = "abcdef"
>>> len(a)
6
>>> a = "abcdef"
>>> a.find("c")
2
>>> a = "abcdef"
#Cut out the 2nd to 3rd characters
>>> print a[1:3]
bc
#Cut out from the first character to the third character
>>> print a[:3]
abc
#Cut out from the 3rd character to the last character
>>> print a[2:]
cdef
#Cut out from the 3rd character to the penultimate character
>>> print a[2:-1]
cde
pattern | order |
---|---|
Integer value from a string | int |
String to decimal value | float |
String from number | str |
Failure example
>>> age = 20
>>> print "I am " + age + " years old!"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
Success story
>>> age = 20
>>> print "I am " + str(age) + " years old!"
I am 20 years old!
--** Array ** in other languages --Some commands that can be used for strings can be used as they are
len
--Check the number of elements>>> sales = [255, 100, 353, 400]
>>> print len(sales)
4
[]
--Cut out>>> sales = [255, 100, 353, 400]
>>> print sales[2]
353
>>> sales = [255, 100, 353, 400]
>>> print 100 in sales
True
range
--Create a list of serial numbers>>> print range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print range(3, 9)
[3, 4, 5, 6, 7, 8]
>>> print range(3, 10, 2)
[3, 5, 7, 9]
sort
--Sort in ascending order
>>> sales = [255, 100, 353, 400]
>>> sales.sort()
>>> print sales
[100, 255, 353, 400]
reverse
--Reverse the order of the elements
--If you want to sort in descending order, sort
and then reverse
>>> sales = [255, 100, 353, 400]
>>> sales.reverse()
>>> print sales
[400, 353, 100, 255]
split
>>> d = "2016/07/15"
>>> print d.split("/")
['2016', '07', '15']
join
>>> a = ["a", "b", "c"]
>>> print "-".join(a)
a-b-c
map
--Instructions that apply function processing to each element of the list
def power(x)
return x * x
print map(power, [2, 5, 8])
#=> [4, 25, 64]
--Basically the same as the list, but it has the feature that the elements cannot be changed. --By showing that the data cannot be changed from the beginning, speed up the calculation and prevent strange mistakes. --You can also use commands like those used in the list
>>> a = (2, 5, 8)
>>> print a
(2, 5, 8)
>>> b = list(a)
>>> print b
[2, 5, 8]
>>> b = [2, 5, 8]
>>> c = tuple(b)
>>> print c
(2, 5, 8)
――It is called a collective type --The elements are lined up and have the characteristic of not allowing duplication.
>>> a = set([1, 2, 3, 4])
>>> print a
set([1, 2, 3, 4])
Duplicates are not displayed
>>> a = set([1, 2, 3, 4, 2, 3])
>>> print a
set([1, 2, 3, 4])
Things that are in a but not in b
>>> a = set([1, 2, 3, 4])
>>> b = set([3, 4, 5])
>>> print a - b
set([1, 2])
What is in both a and b
>>> a = set([1, 2, 3, 4])
>>> b = set([3, 4, 5])
>>> print a | b
set([1, 2, 3, 4, 5])
Duplicates in a and b
>>> a = set([1, 2, 3, 4])
>>> b = set([3, 4, 5])
>>> print a & b
set([3, 4])
>>> a = set([1, 2, 3, 4])
>>> b = set([3, 4, 5])
>>> print a ^ b
set([1, 2, 5])
--Something like an associative array or hash in other languages
--Basically, a pair of key
and value
>>> sales = {"hoge":200, "hogehoge":300, "hogeo":500}
>>> print sales
{'hogeo': 500, 'hogehoge': 300, 'hoge': 200}
>>> sales = {"hoge":200, "hogehoge":300, "hogeo":500}
>>> sales["hogehoge"] = 800
>>> print sales
{'hogeo': 500, 'hogehoge': 800, 'hoge': 200}
>>> sales = {"hoge":200, "hogehoge":300, "hogeo":500}
>>> print "hoge" in sales
True
>>> sales = {"hoge":200, "hogehoge":300, "hogeo":500}
>>> print sales.keys()
['hogeo', 'hogehoge', 'hoge']
>>> sales = {"hoge":200, "hogehoge":300, "hogeo":500}
>>> print sales.values()
[500, 800, 200]
>>> sales = {"hoge":200, "hogehoge":300, "hogeo":500}
>>> print sales.items()
[('hogeo', 500), ('hogehoge', 800), ('hoge', 200)]
item | English | meaning |
---|---|---|
%d | decimal | integer |
%f | float | Decimal |
%s | string | String |
>>> a = 10
>>> b = 1.234234
>>> c = "hoge"
>>> d = {"hoge":200, "hogehoge":500}
>>> print "age: %d" % a
age: 10
>>> print "price: %f" % b
price: 1.234234
>>> print "name: %s" % c
name: hoge
Display 10 digits
>>> print "age: %10d" % a
age: 10
Fill the remaining digits with 0
>>> print "age: %010d" % a
age: 0000000010
Display up to 2 decimal places
>>> print "price: %.2f" % b
price: 1.23
In the case of dictionary type, the value of a specific key can be retrieved.
>>> print "sales: %(hoge)d" % d
sales: 200
Specify multiple values at the same time
>>> print "%d and %f" % (a, b)
10 and 1.234234
score = 70
if score > 60:
print "OK!"
#=> OK!
score = 70
if score > 60 and score < 80:
print "OK!"
#=> OK!
Can be written like this
score = 70
if 60 < score < 80:
print "OK!"
#=> OK!
/ ʻelif
score = 45
if score > 60:
print "ok!"
elif score > 40:
print "soso..."
else:
print "ng!"
#=> soso...
Can be written like this
score = 45
print "OK!" if socre > 60 else "NG!"
#=> NG!
for
sales = [13, 3423, 31, 234]
sum = 0
for sale in sales:
sum += sale
print sum
#=> 3701
Can be written like this
sales = [13, 3423, 31, 234]
sum = 0
for sale in sales:
sum += sale
else:
print sum
#=> 3701
for i in range(10):
print i
#=> 0..Up to 9 is displayed
continue
for i in range(10):
if i == 3:
continue
print i
#=>0 excluding 3..Up to 9 is displayed
break
for i in range(10):
if i == 3:
break
print i
#=> 0..Up to 2 is displayed
--ʻIter stands for ʻiteration
Display dictionary items
users = {"hoge":200, "hogehoge":300, "hogeo":500}
for key, value in users.iteritems():
print "key: %s value: %d" % (key, value)
#=> key: hogeo value: 500
#=> key: hogehoge value: 300
#=> key: hoge value: 200
Display the dictionary key
users = {"hoge":200, "hogehoge":300, "hogeo":500}
for key in users.iterkeys():
print key
#=> hogeo
#=> hogehoge
#=> hoge
Display the dictionary value
users = {"hoge":200, "hogehoge":300, "hogeo":500}
for value in users.itervalues():
print value
#=> 500
#=> 300
#=> 200
while
n = 0
while n < 5:
print n
n += 1
else:
print "end"
#=> 0
#=> 1
#=> 2
#=> 3
#=> 4
#=> 5
#=> end
end is not displayed
n = 0
while n < 5:
if n == 3
break
print n
n += 1
else:
print "end"
#=> 0
#=> 1
#=> 2
Uninflected word
def hello():
print "hello"
hello()
#=> hello
Use arguments
def hello(name):
print "hello %s" % name
hello("tom")
#=> hello tom
Use arguments
def hello(name):
print "hello %s" % name
hello("tom")
hello("bob")
#=> hello tom
#=> hello bob
Use two arguments
def hello(name, num):
print "hello %s! " % name * num
hello("tom", 2)
hello("bob", 3)
#=> hello tom! hello tom!
#=> hello bob! hello bob! hello bob!
Give the argument a default value
def hello(name, num = 3):
print "hello %s! " % name * num
hello("tom", 2)
hello("bob")
#Can be written like this
hello(num = 2, name = "serve")
#=> hello tom! hello tom!
#=> hello bob! hello bob! hello bob!
#=> hello steve! hello steve! hello steve!
Have a return value
def hello(name, num = 3):
return "hello %s! " % name * num
s = hello("bob")
print s
#=> hello bob! hello bob! hello bob!
lambda
)def power(x):
return x * x
print map(power, [2, 5, 8])
#=> [4, 25, 64]
Can be written like this
print map(lamdba x:x * x, [2, 5, 8])
#=> [4, 25, 64]
pass
**--The name
defined inside the function is different from the name
defined outside the function.
name = "hoge"
def hello():
name = "hogehoge"
print name
#=> hoge
--If you can define a function called hello2 ()
and write the contents later, indenting it after the colon and writing pass
means that nothing will be processed.
def hello2()
pass
the term | Description |
---|---|
object | A collection of variables and functions |
class | Blueprint of the object |
instance | A materialized class |
class User(object):
def __init__(self, name):
self.name = name
def greet(self):
print "my name is %s!" % self.name
bob = User("Bob")
tom = User("Tom")
print bob.name
bob.greet()
tom.greet()
#=> Bob
#=> my name is Bob!
#=> my name is Tom!
--Inherit if you want to create an object with slightly different properties while keeping the properties of the class
class User(object):
def __init__(self, name):
self.name = name
def greet(self):
print "my name is %s!" % self.name
class SuperUser(User)
def shout(self)
print "%s is SUPER!"
bob = User("Bob")
tom = SuperUser("Tom")
tom.greet()
tom.shout()
#=> my name is Tom!
#=> Tom is SUPER!
--A module is a collection of useful instructions that Python has prepared in advance. -Module list on official website --If you want to call multiple modules, separate them with commas.
math module
import math
print math.ceil(5.2)
#=> 6.0
random module
import random
for i in range(5):
print random.random()
#=> 0.761598550441
#=> 0.180484460723
#=> 0.494892311516
#=> 0.672065106987
#=> 0.561810023764
When calling only a part of the module
from datetime import date
print date.today()
2016-07-13
Recommended Posts