Getting Started with Python

** Introduction **

I tried an introduction to Python for dot installation, so it's a study record!

environment

Overview

--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 andpass`

** Basic Python practices **

Add coding: UTF-8

If not attached

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

When attached

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!

Coding convention

--See Python Code Style Guide

Other

--You can use ; to separate sentences, but it is not recommended. --The extension is .py --Comment is # --Strict indentation

** Variables and data types **

variable

--Label attached to data --Case sensitive

Data types that can be handled by Python

--Numerical value --String --Authenticity value --List (array) --Tuple --Dictionary (associative array, hash)

** Numerical value **

Numerical values that can be handled by Python

--Integer --Decimal --Complex number

operator

item operator
addition +
subtraction -
multiplication *
division /
quotient //
remainder %
Exponentiation **

Rules for calculation

--When you operate an integer and a decimal, the result is always a decimal. --Division between integers is a truncated integer

** String **

When dealing with Japanese

There is a case in which the following as 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

String arithmetic

Linking

>>> print "Hello " + "World!"
Hello World!

repetition

>>> print "Hello World! " * 3
Hello World! Hello World! Hello World!

Escape strings

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>

** String manipulation instructions **

Counting the number of characters

>>> a = "abcdef"
>>> len(a)
6

Search for strings

>>> a = "abcdef"
>>> a.find("c")
2

Cut out a character string

>>> 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

** Mutual conversion between numbers and strings **

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!

list

What is a list?

--** 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

ʻIn` --Existence check

>>> 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]

** Convenient instructions that can be used in the list **

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]

** Tuple **

--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

Change from tuple to list

>>> a = (2, 5, 8)
>>> print a
(2, 5, 8)
>>> b = list(a)
>>> print b
[2, 5, 8]

Change from list to tuple

>>> b = [2, 5, 8]
>>> c = tuple(b)
>>> print c
(2, 5, 8)

set

――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])

Set arithmetic

Difference set

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])

Union

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])

Intersection

Duplicates in a and b


>>> a = set([1, 2, 3, 4])
>>> b = set([3, 4, 5])
>>> print a & b
set([3, 4])

Only one

>>> a = set([1, 2, 3, 4])
>>> b = set([3, 4, 5])
>>> print a ^ b
set([1, 2, 5])

dictionary

--Something like an associative array or hash in other languages --Basically, a pair of key and value

Basic usage

>>> 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}

Confirmation of key existence

>>> sales = {"hoge":200, "hogehoge":300, "hogeo":500}
>>> print "hoge" in sales
True

Check the list of keys

>>> sales = {"hoge":200, "hogehoge":300, "hogeo":500}
>>> print sales.keys()
['hogeo', 'hogehoge', 'hoge']

Check the list of values

>>> sales = {"hoge":200, "hogehoge":300, "hogeo":500}
>>> print sales.values()
[500, 800, 200]

Check both lists

>>> sales = {"hoge":200, "hogehoge":300, "hogeo":500}
>>> print sales.items()
[('hogeo', 500), ('hogehoge', 800), ('hoge', 200)]

** Embed data in string **

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

** Conditional branch with ʻif` statement **

Basic conditional branching

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!

Conditional branching by ʻelse / ʻ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!

** Loop processing **

Loop with 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

Loop in dictionary

--ʻ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

Loop with 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

function

Basic function

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!

Anonymous function (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]

** Variable scope and 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

object

Glossary

the term Description
object A collection of variables and functions
class Blueprint of the object
instance A materialized class

Creating a 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!

Classes and inheritance

--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!

** Try using the module **

--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

1.1 Getting Started with Python
Getting Started with Python
Getting Started with Python
Getting Started with Python Functions
Getting Started with Python Django (4)
Getting Started with Python Django (3)
Python3 | Getting Started with numpy
Getting Started with Python Django (5)
Getting Started with Python responder v2
Getting Started with Python Web Applications
Getting Started with Python for PHPer-Classes
Getting Started with Python Basics of Python
Getting Started with Python Genetic Algorithms
Getting started with Python 3.8 on Windows
Getting Started with Python for PHPer-Functions
Django 1.11 started with Python3.6
Getting Started with Golang 2
Getting started with apache2
Getting Started with Django 1
Getting Started with Optimization
Getting Started with Golang 3
Getting Started with Numpy
Getting started with Spark
Getting Started with Pydantic
Getting Started with Golang 4
Getting Started with Jython
Getting Started with Django 2
Getting Started with python3 # 1 Learn Basic Knowledge
Getting Started with Python Web Scraping Practice
Getting Started with Python Web Scraping Practice
Getting started with Python with 100 knocks on language processing
Translate Getting Started With TensorFlow
Getting Started with Tkinter 2: Buttons
Getting Started with Go Assembly
started python
Getting started with AWS IoT easily in Python
Get started with Python! ~ ② Grammar ~
Getting Started with Django with PyCharm
Materials to read when getting started with Python
Settings for getting started with MongoDB in python
Getting Started with python3 # 2 Learn about types and variables
Getting Started with Google App Engine for Python & PHP
Get started with Python! ~ ① Environment construction ~
Link to get started with python
Getting Started with Git (1) History Storage
Getting started with Sphinx. Generate docstring with Sphinx
Getting Started with Sparse Matrix with scipy.sparse
Getting Started with Cisco Spark REST-API
Getting started with USD on Windows
Get started with Python in Blender
Getting Started with CPU Steal Time
FizzBuzz with Python3
Scraping with Python
Statistics with python
Getting Started with python3 # 3 Try Advanced Computations Using Import Statements
Scraping with Python
Python with Go
Twilio with Python
Play with 2016-Python
Tested with Python
Getting Started with Mathematics Starting with Python Programming Challenges Personal Notes-Problem 1-1