This is a memo of what I learned for studying python. Please point out any errors.
python
#Type conversion
#Convert to int
int("100") #Decimal number
int("100", 2) #Binary number
int("100", 16) #Hexadecimal
#Convert to float value
float()
#Convert to string
str()
#Character output
print("String")
print("String"+"String2") # Stringを連結する
print("String"+ str(100)) #Convert numbers to letters and concatenate
print("String",100) #Letter and number concatenation(There is a space in between)
#Character input
test = input()
#total
list = [1,2,3]
sum(list) #result: 6
#Maximum value
max(list) #result: 3
#minimum value
min(list) #result: 1
#length
len(list) #result: 3
python
loop = [0,1,2,3]
#Loop for the number of arrays
for i in loop:
#Loop contents
#Loop for the specified number of times
for i in range(5):
#Loop contents
#Loop in a specific range
for i in range(2,4):
#Loop contents
cnt = 1
while cnt <= 10:
print(cnt)
cnt = cnt + 1 #Count addition
Control minutes | Description |
---|---|
break | Break out of the loop(End) |
continue | Return to the beginning of the loop |
else | Run at the end of the loop |
else is executed after the loop ends. However, if the break statement breaks the loop, else will not be executed.
Class=["Tanaka","Suzuki","Sato"]
check ="Tanaka"
#Check if "Yamada" is in the class name
for name in Class:
if check == name:
print(name+"Is a classmate")
break
else:
print(check +"Is not a classmate")
python
testA = 1
if 1 == test:
#Processing at True
else:
#Processing when false
testB = "TEST"
if "T" in testB:
#Processing at True
elif "B" in testB:
#Processing when true
operator | Description |
---|---|
A == B | A and B are equal |
A != B | A and B are different |
A > B | A is greater than B |
A < B | A is smaller than B |
A >= B | A is B or higher |
A <= B | A is less than B |
A in B | Element of A exists in B |
operator | Description |
---|---|
A and B | A and B |
A or B | A or B |
A < B and B < C In such a case, you can also write as follows A < B < C
operator | Description |
---|---|
A | B | Logical sum(OR) |
A & B | Logical AND(AND) |
A ^ B | Exclusive OR(XOR) |
A << B, A >> B | Shift operation |
def Name1():
#Function processing
return 0
#Define default arguments
def Name1():
#Function processing
return 0
#Define default arguments
def Name2(name="Anonymous"):
print( "What's your name" + name + "is" )
#Define default arguments
def NameAndAge(name="Anonymous", age=25):
print( "What's your name" + name + "is" )
print( "How old are you" , age,"I'm talented" )
#Specify keywords
NameAndAge(age=12, name="Taro")
import random #Load the module
import random as rm #Specify a name for the module
from statistics import median #Load the function in the module
from statistics import * #Load all functions in the module
Model name | Description |
---|---|
int | Integer type |
float | Floating point type |
complex | Complex type |
XX base | Notation | Convert from decimal | XX baseから10進数に変換 |
---|---|---|---|
Hexadecimal | 0xffff | hex(65535) | int("0xffff",16) |
Binary number | 0b1111 | bin(15) | int("0b1111",2) |
8 base | 0o777 | oct(511) | int("0c777",8) |
Model name | Description |
---|---|
str | String type |
bytes | Handles character strings read from files, etc. |
test = "ABCDE"
test2 = test.replace("B","O") #Replace B with O
test3 = test.replace("B","") #Delete B
#However, the original variable does not change
test # "ABCDE"
test2 # "AOCDE"
test3 # "ACDE"
test = "1 2 3 4 5"
#Divide by space
test_split = test.split(" ")
#[.]With test_Concatenate split data
test_join = ".".join(test_split )
test # "1 2 3 4 5"
test_split # ["1","2","3","4","5"]
test_join # "1.2.3.4.5"
Method | Description |
---|---|
str.find(Search character[ ,start,End] ) | Search for a string from the beginning,When it doesn't hit**-1**return it |
str.rfind(Search character[ ,start,End] ) | Search for a string from the end,When it doesn't hit**-1**return it |
str.index(Search character[ ,start,End]) | Search for a string from the beginning,When it doesn't hitValueErrorreturn it |
str.rindex(Search character[ ,start,End]) | Search for a string from the end,When it doesn't hitValueErrorreturn it |
str.startwith(Search character[ ,start,End]) | Search charactersostartWhen you areTruereturn it |
str.endwith(Search character[ ,start,End]) | Search charactersoEndWhen you areTruereturn it |
Insert a string using format
test= "my name is{}is"
test.format("Taro") # 私の名前はTaroです
#Specify the order
test ="His name is{0}is.{0}Age{1}才is."
test.format("Jiro","25") # 彼の名前はJiroです。Jiroの年齢は25才です。
#Specify keywords
test ="His name is{Name}is.{Name}Age{Age}才is."
test.format(Name="Jiro",Age="25") # 彼の名前はJiroです。Jiroの年齢は25才です。
#Specify in the dictionary
test = "{0[name]}Is{0[age]}I'm talented"
dictionary = {'name':'Taro' , 'age':'14'}
test.format(dictionary) #Taro is 14 years old
#Specify notation
test = "my name is{:>10}is" #Right justified
test.format("Taro") # 私の名前は Taroです
test = "{:.1%}"
test.format(0.25) # 25.0%
#Display as f character string(python3.6 or later)
name="Taro"
f"my name is{name}is"
letter | Description |
---|---|
\n | new line |
\r | new line(CR) |
\t | Horizontal tab |
\f | New Page |
' | Single quote |
" | Double quotation |
\|backslash | |
\0 | null |
If r is added, the character is displayed as it is.
raw = r"c:\Users\XX\Document"
Get True or False values
Refers to the one in which multiple elements are arranged in order.
python
#List declaration
list = [1,2,3]
list2= [2,3,4]
#List concatenation
list3 = list + list2
list3 #result: [1,2,3,2,3,4]
#Specify the beginning
list[0] = 0
list #result: [0,2,3]
#Specify the end
list[-1] = 1
list #result: [0,2,1]
#Slice specification
slice = [0,1,2,3,4,5]
slice[1:3] # [1,2]
slice[:4] # [0, 1, 2, 3]
slice[3:] # [3, 4, 5]
#Specify an even number
slice[::2] # [0,2,4]
#Replace with slice
slice[1:2] = [10,11]
slice # [0, 'a', 'b', 2, 3, 4, 5]
#Delete with slice
slice = [0,1,2,3,4,5]
del slice[4:]
slice # [0, 1, 2, 3]
#Delete element
list = [0,1,2]
del list[2]
list #result: [0,1]
#Sorting elements(ascending order)
list = [3,5,2,1,0]
list.sort()
list # [0, 1, 2, 3, 5]
#Sorting elements(descending order)
list = [3,5,2,1,0]
list.sort(reverse=True)
list # [5, 3, 2, 1, 0]
#Customize the sort
#Sort in descending order of the sum of the numbers in the array
def sumAll(num):
#Sum and return the numbers in the array
return num[0] + num[1] + num[2]
list = [[10, 50, 30],[20, 50, 40],[80, 60, 70]]
list.sort(key=sumAll, reverse=True)
list # [[80, 60, 70], [20, 50, 40], [10, 50, 30]]
Method name | Description |
---|---|
reverse() | Reverse order |
remove() | remove |
append() | Add element at the end |
expend() | Add sequence at the end |
pop() | Delete the end and return the deleted value |
index() | Find the element you want to search for and return the index. Returns ValueError if not found |
Tuples look a lot like lists, but you can't change the elements.
#Tuple declaration
Months =("Jan","Feb","Mar","Apr","May","Jun","Jul")
#Or
Months ="Jan","Feb","Mar","Apr","May","Jun","Jul"
#When there is one element, put a comma at the end
Day= ("Mon",)
#Connection is OK
Months = Months + ("Aug","Sep","Oct","Nov","Dec")
#Unpack assignment
a = 1
b = 2
a , b = b , a
a # 2
b # 1
Tuples are sequences that cannot be changed, so dictionary keys and Can be an element of set
#Register your birthday in the dictionary
birthdays = {("April","1 day"):"Yamada Taro",
("June","The 6th"):"Hanako Yamada",
("November","11th"):"Jiro Yamada"}
#Specify date
birthday =("June","The 6th")
#Find a matching key in the for statement
for day in birthdays:
if birthday == day:
print(birthdays[day]) #Hanako Yamada
break
set Data used to manage non-overlapping elements
test1 = {1,2,3}
test2 = {3,4,5}
#Union
test1 | test2 # {1, 2, 3, 4, 5}
test1.union(test2) # {1, 2, 3, 4, 5}
#Difference set
test1 - test2 # {1, 2}
test1.difference(test2) # {1, 2}
#Logical AND
test1 & test2 # {3}
test1.intersection(test2) # {3}
#Exclusive OR
test1 ^ test2 # {1, 2, 4, 5}
test1.symmetric_difference(test2) # {1, 2, 4, 5}
#Convert from list to set
list = [1,2,3,4,5]
set(list) # {1, 2, 3, 4, 5}
#Comparison
testA = {1,2,3,4,5,6}
testB = {3,4,5}
Check = testA & testB
if 4 in Check:
print("4 is included in Test A and Test B")
if {3,4} <= Check:
print("3,4 is included in Test A and Test B")
Manage the array by associating Key and Value
#Define dictionary type
test = { "name": "Taro",
"age": "25"
"Birthplace": "Tokyo"}
# dict()Defined using
dict([['key1','value1'],['key2','value2']]) # {'key1': 'value1', 'key2': 'value2'}
dict(key1='value1', key2='value2') # {'key1': 'value1', 'key2': 'value2'}
#to add
test ={'name':'Taro'} # {'name': 'Taro'}
test["sex"] ="Man"
test # {'name': 'Taro', 'sex': 'Man'}
#Combine with update method
test = {'name': 'Taro', 'sex': 'Man'}
test.update({'sex':'woman','age':'12 years old'})
test # {'name': 'Taro', 'sex': 'woman', 'age': '12 years old'}
#delete
test = {'name': 'Taro', 'sex': 'Man'}
del test["sex"]
test # {'name': 'Taro'}
#Check the existence of the element and add the element
test = {'name':'Goro','age':'12'}
word = "age"
if word in test:
#Exists
test[word] = test[word]+'Talent'
else:
#not exist
test[word] = 'Blank'
test
#Add elements using get
test = {'name':'Goro'}
word = "age"
test[word] = test.get(word, 'Blank')
test # {'name': 'Goro', 'age': 'Blank'}
Data type | type |
---|---|
list | Can be changed(mutable) |
dictionary | Can be changed(mutable) |
set | Can be changed(mutable) |
bytearray | Can be changed(mutable) |
Tuple | Cannot be changed(immutable) |
str/bytes | Cannot be changed(immutable) |
#At the beginning of the comment#Put on
docstring Add a description of the function using docstring
def docstring():
'''
docstring test
Test 1
Test 2
Test 3
'''
Test = "ran docstring"
print(Test)
print(docstring.__doc__) #Get the explanation of docstring as a string
help(docstring) #Check the explanation of the function from help
Recommended Posts