Python basics summary

What is Python

An object-oriented language that is simple and easy to learn. It is adopted by Google App Engine, and there is a framework called Django.

Run python

Interactive mode

$python

Hit to enter interactive mode.

python
>>>

If you write it here, it will be executed immediately. It looks like the following.

python
>>>print "hello world"
exit()

You can get out with.

Write to file and execute

hello.py


print "hello world"

Create and execute a file like

$python hello.py

Precautions for execution

variable

msg = "hello world"
print msg

The output of hello world. Uppercase and lowercase letters are treated as different things.

Data type

Numeric type

Integer, decimal, complex Operator +-* / //% ** etc.

print 10 * 5 #50
print 10 // 3 #3
print 10% 3 #1
print 2**3 #8

String

“hello” ‘hello'If you do like this, it will be a character string. However, in the case of the Japanese, `u" Hello "` put u like.

Line breaks are reflected when enclosed in "" "

print """<html lnag="ja">
<body>
</body>
</html>"""

escape

Escapes like \ t \ n are available.

Number of characters len, search find, cut out []

s = "abcdefgh"
#String length
print len(s)
#Character position
print s.find("c") #2 Counting from 0
#Cut out characters[Th:word count]
print s[2] #c
print s[2:5] #cde
print s[:5] #abcde
print s[2:-1] #cdefgh

Mutual conversion between numbers and strings

Number <> string -Convert from string to number int float


print 5 + int("5") %10
print 5 + float("5") %10.0

-Convert from numerical value to character string str

age=20
print "i am" + str(age) + "years old!"

list

Length len, Join +, Repeat *, Get Element [], Existence of Element in

sales = [255, 100, 353, 400]

print len(sales) #4 Extract the length of the array
print sales[1] #Acquisition of 100 elements
print sales + sales #Joining arrays[255, 100, 353, 400, 255, 100, 353, 400]
print sales *3 #Array iteration[255, 100, 353, 400, 255, 100, 353, 400, 255, 100, 353, 400]
print 100 in sales #true in element existence judgment

range

Array creation

range(10) #[1,2,3,4,5,…8,9]Up to 9
range(3, 10) #[3,4,5,…8,9]From 3 to 9
range(3, 10, 2) #[3,5,7,9]Skip 2 from 3 to 9

List operations sort, reverse, split, join

#Sort in ascending order
sales.sort()
#Reverse the list
sales.reverse()
#String → list split
d = "2013/12/15"
print d.split("/") #['2013', '12', '15']
#List → string join
a = ['a', 'b', 'c']
print '-'.join(a) #a-b-c

Tuple

It feels like a = (2, 5, 8). You can connect and repeat just by not being able to change the contents of the elements. → Prevent strange mistakes and increase the calculation speed.

Mutual conversion of tuples and lists

#Tuple → list
b = list(a)
#List → Tuple
c = tuple(b)

set

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

Do not allow duplicate elements print aIs 3,2 is duplicated and ignored.

Collective type

#Difference set
print a - b
#Union
print a | b
#Only common terms
print a & b
#Items on only one side
print a ^ b

Dictionary type data key value

[2505, 523, 500]
{"apple":200, "orange":300, "banana":500}
print sales; #The order may change
print sales["apple"] #200
sales["orange"] = 800 #Change value
print sales #{'orange': 800, 'apple': 200, 'banana': 500}
print "orange" in sales #true Existence judgment

print sales.keys() #key list
print sales.values() #list of values
print sales.items() #key-list of values

Embed data in a string

a = 10
b = 1.232323
c = "apple"
d = {"orange":200, "banana":500}
print "age: %d" % a
print "age: %10d" % a #10 digits
print "age: %010d" % a #Fill with 10 digits 0
print "price: %f" % b
print "price: %.2f" % b
print "name: %s" % c

print "sales: %(orange)d" %d
print "%d and %f" % (a, b)

if statement

scoe = 70
if score > 60:
     print "ok!"
     print "OK!"

#Comparison operator> < >= <= == !=
#Logical operator and or not

if score > 60 and score < 80:
     print "ok!"
     print "OK!"

if 60 < score <80
     print "ok!"
     print "OK!"

score = 70
if score > 60:
     print "ok!"
elif score > 40:
     print "soso…"
else:
     print "ng!"

print "OK!" if score > 60 else "NG!"

for statement

sales = [13, 43, 4233, 2343]
for sale in sales:
     sum += sale
else:
     print sum

#* You can write a process to be executed only once when the for statement is exited with the else of the for statement.

for i in range(10)
     if i == 3:
          continue #Skip the loop
      if i == 3:
          break #End the loop
     print i
#From 0 to 9.

for i in range(1, 101)
     #processing
#i loops from 1 to 100

Dictionary type for loop

users = {"apple":200, "orange":300, "banana":500}
for key, value in users.iteritems()
     print "key: %s value: %d" % (key, value)
for key, value in users.iterkeys()
     print key
for value in users.itervalues()
     print value

while statement

n = 0
while n < 10
     print n
     n = n + 1
     n += 1
else:
     print "end"
#continue, break,else is the same as the for statement.
#If you use break, the else clause will not be executed either.

function

def hello():
     print "hello"
hello()

#argument
def hello(name, num = 3):
     print "hello %s" %name * num
hello(name = "tom", num =2) #If you give it a name, you can change the order of the arguments.
hello("steve")

def hello(name, num = 3):
     return "hello %s" %name * num
s = hello("steve")
print s

Variables and scope, pass

name = "apple"
def hello():
     name = "orange"
print name

#pass
def hello2():
     pass
#If you create a function called hello2 for the time being and write pass when the contents are empty, it's okay.
#In other languages,{}You can indicate the end of the function so that it can be displayed, but in python you can not indicate the end, so write pass instead.

Actions for map, lambda-list

#map-Execute a function for each element of the list
def double(x):
    return x*x
print map(double, [2, 5, 8])

#lamda anonymous function-used when you want to use the function directly when using map
print map(lambda x:x*x, [2, 5, 8])

Creating an object

Object (a collection of variables and functions) Class: Object blueprint 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()

Class inheritance

class SuperUser (User):
def shout(self):
     print :"%s is SuPER!" % self.name

tom = SuperUser("Tom")
tom.shout()

Use of modules

import math, random
from datetime import date
print math.ceil(5.2) #6.0
for i in range(5)
     print random.random()
print date.today()

reference

Introduction to Dot Install Python

Recommended Posts

Python basics summary
Python basics ⑤
Python Summary
Python basics
Python basics ④
Python summary
Python basics ③
Python basics
Python basics
Python basics
Python basics ③
Python basics ②
Python basics ②
Python basics: list
Python basics memorandum
Python tutorial summary
Python CGI basics
Python basics: dictionary
Basics of Python ①
Basics of python ①
Python slice basics
#Python basics (scope)
#Python basics (#Numpy 1/2)
#Python basics (#Numpy 2/2)
#Python basics (functions)
Python basics: functions
#Python basics (class)
Summary about Python scraping
Python Django tutorial summary
Python basics ② for statement
Python: Unsupervised Learning: Basics
Python basics 8 numpy test
Summary about Python3 + OpenCV3
Errbot: Python chatbot basics
Python function argument summary
#Python DeepLearning Basics (Mathematics 1/4)
Python basics: Socket, Dnspython
Python directory operation summary
Python AI framework summary
Python iteration related summary
# 4 [python] Basics of functions
Summary of Python arguments
Basics of python: Output
Python3 programming functions personal summary
Summary of python file operations
Python
What's new in Python 3.10 (Summary)
Standard input / summary / python, ruby
Python class member scope summary
python pandas study recent summary
Python data type summary memo
Python basics: conditions and iterations
Face detection summary in Python
Paiza Python Primer 4: List Basics
What's new in Python 3.9 (Summary)
Basics of Python × GIS (Part 1)
Python Crawling & Scraping Chapter 4 Summary
Virtual Environment Version Control Summary Python
Basics of Python x GIS (Part 3)
Paiza Python Primer 5: Basics of Dictionaries
SNS Python basics made with Flask