PyQ ~ Python First Steps ~


print ( )  #display. Enclose the character string in "" or "". The numbers remain the same.
print ( a + b )  #Character strings can be combined as shown on the left.
print (letter+ str (Numbers) )  #Pay attention to the type when joining.
print ( a , b , c )  #The result of this execution is a b c.
print ( a , b , c , sep = " " )  #abc is the result.

#usually,When separated by, a half-width space is inserted by default.
#Also,When separating with, there is no problem even if the molds are mixed separately.
#The delimiter can be changed from half-width by the character string specified by sep.

new line= /n
tab= /t

print("""/
...
...
... """)  # /It is also possible to write from the first line without entering.

len(variable)  # variableの文字数をカウントして出力することが可能。

#When specifying a character string in the variable()Line breaks are also free if you come out.
#However, the parts other than "" are not reflected, and line breaks are also included.\Only when indicated by n.
#For text*It is also possible to repeat by setting 3 etc.
#Syntax Error is an error that the code is written or the syntax is incorrect.

#The following error is sometimes called Exception compared to Syntax Error.
#Name Error is an error that occurs when an undefined variable name is used.
#Identification Error is an error that has unnecessary white space or does not have necessary white space.
#Type Error is an error that uses an object of an inappropriate type in a function or the like.

#What is a type str(String)・ Int (integer) ・ float (floating point number).
#The quotient becomes a float type. Also, although this rarely appears, there is also a complex number complex.
#Almost no more, but bool (True)/False) ・ NonType (None) also exists.
 +    #addition
 -    #subtraction
 *    #multiplication
 /    #Division (penetrate to the decimal point)
 //   #Division (integer with decimal point rounded down)
 %    #Too much division
 **   #Exponentiation
a = b  #Substitute b for a. It will be overwritten each time it is assigned.

a += 2 #Increase the value of a by 2. a=a+A syntax that has the same meaning as 2.
a -= 2 #Decrease the value of a by 2. a=a-A syntax that has the same meaning as 2.
a *= 2 #Multiply the value of a by 2. a=a*A syntax that has the same meaning as 2.
a /= 2 #Divide the value of a by 2. a=a/A syntax that has the same meaning as 2.

a == b  #a and b are equal (if ,,,
a != b  #a and b are not equal (if ,,,
a > b  #a is greater than b (if ...
a < b  #b is greater than a (if ...
a >= b  #If a is greater than or equal to b (in the case of, ...
a <= b  #b is greater than or equal to a (in the case of, ...

and  #Multiplying conditions (logical product)
or  #One of the conditions (logical sum)
not  #Show denial
if conditional expression:
processing........
elif conditional expression:
processing........
elif conditional expression:
processing........
else:
processing........

#If you use if a in dictionary, check if the dictionary contains a. The dictionary can be a list.
#On the contrary, if you want to do it if it is not included, you can do it with not in.
#Nesting control structures such as if, for, and While is called nesting.
numbers = [ aaa , bbb , ccc , ddd … ] #index
x = numbers[0] #  aaa
print(numbers[1:3])  # bbb,ccc
print(numbers[:2])  # aaa,bbb
print(numbers[2:])  # ccc,ddd

#List name[Reference point]Can be specified with.
#Regarding the reference points, from 0 in order from the left, from the right-Specify from 1.
#list[ ]There is no concept of type. There is a type( )in the case of.
#Index from 0 in ascending order from left, index from right-It starts from 1 in descending order.

print(numbers[Position 1:Position 2:2])  # aaa,ccc

#Position 1 indicates the start position, position 2 indicates the end position, and 2 indicates the step (every 2) count.

x = aaa , bbb , ccc , ddd … #When there is such a list
numbers = x.split(",") #This is an index.","Is the delimiter.

#Also, if it is a list, use a dictionary when you forget where and what number you put.
#By doing this, it is possible to pull out by name, not by index position.

with open("xxx/xxx.csv",encoding="utf-8") as f:
    f.readlines() #It is possible to list by line

numbers = {}
numbers["name"] = aaa
numbers["Street address"] = bbb
numbers["sex"] = ccc
numbers["age"] = ddd

numbers[key] = value  #When officially shown, it looks like this.

#At this time, the place that normally corresponds to the index is called Key, and the value is called Value.

numbers = {"name":"aaa","Street address":"bbb","sex":"ccc","age":"ddd"}

#Key like this:It is also possible to type in the dictionary as it is by writing it in Value.

del numbers["name"]  #By doing this, the corresponding item can be deleted.

numbers.pop("name")  #This is the same process as above.
numbers.get("a","b")  #If there is an item called a, its Value, if not, b.

#If b is not set in get or blank in return, None will be the return value.

numbers.keys()  #Extract the key in the form of a list. dict_keys()Comes to my head.
list(numbers.keys()) #If you make this shape. You can get rid of your head and list it completely.

numbers.values()  #Extract values in the form of a list. dict_values()Comes to my head.
list(numbers.values()) #If you make this shape. You can get rid of your head and list it completely.

numbers.items()  #Extract items in the form of a list. dict_items()Comes to my head.
list(numbers.items()) #If you make this shape. You can get rid of your head and list it completely.
x.append ( "Additional elements" ) #Add the elements in parentheses to the end of the list.
x.insert (insert position, "Additional elements" )  # Additional elementsを指定の位置に挿入。
x.pop (position)  #Delete the value at the specified position. If there is no entry, the last value is deleted.
for x in list:  #Assign each element of the list to x for processing.
processing........

for key in dictionary name:  #Substitute the dictionary keys in order. It can be the key x.
processing........
    print(key)  #Show Key
    print(Dictionary name[key])   #Show Value

for key,value in dictionary name.items() #key and value are arbitrary strings.
processing........
    print(key)  #Show Key
    print(value)   #Show Value

pass  #Used when you want to finish without executing anything, but you get a syntax error if you do not write anything.
break  #If there is a condition that you want to stop iterative processing~~ :End with break.
continue  #It can be used when you want to skip the iterative process only that time.

f = open ( "file name" , encoding = "utf-8" ) 
x = f.read()  #read and name it x
f.close()  #close

#In the above method, it is easy to forget to close, and in most cases it opens in the following form and is automatically closed.

with open ( "file name" , "How to call" , encoding = "utf-8" ) as f

# r :Read-only. (Cannot be written.) Can be omitted.
# w :Call when writing. If the file does not exist, create a new one.
# x :Create and write the file only if the file does not exist.
# a :Write at the end. If the file does not exist, create a new one.
with open ( "file name" , "How to call" , encoding = "utf-8" ) as f
    for x in f: #Extract line by line from f
        print(x)  #On each line\n is print\Since n is added, there is a space between lines.

x.strip()  #Omit the blank elements that exist at both ends.
x.rstrip()  #Omit the blank element that exists at the right end.
x.lstrip()  #Omit the blank element that exists at the left end.

#Also, when calling it, it is called with the basic character string str, so if you want to calculate numbers, int conversion is required.

x.split(",")  # ,Split the text with.
x.join(",".join(list))  # ,を区切り文字にlistをテキストに結合する。 
x.replace("Original string","Replacement string","Number of replacements")  # Number of replacementsは制限なし。省略可。]

"text%dtext" %variable#Use the value of a variable. (Number string)
"text%stext" %variable#Use the value of a variable. (Character string)

print("{1},{2}!!".format("Say","Hello"))  #Use the format element with index specification.
{:d}  #Display the specified number as an integer system
{:5d}  #Displayed in integer system, then right-justified with 5 digits
{:05d}  #Same as above, but the remaining digits are filled with 0 and displayed
{:,d}  #Show comma-separated integer values every 3 digits
{:f}  #Display the specified number up to 6 decimal places
{:.3f}  #Display the specified number up to 3 decimal places
"text{name}text".format( name = "xxx" ) #You can also insert it later.

#format is nothing{}If you don't put it inside, you will feel like you are going to apply it in order from the front.

x.startswith("Yamada")  # Yamadaから始まる
x[:2] == "Yamada"  # 最初の2文字がYamada
x.find("Yamada") = = 0  # Yamadaを探したら先頭にあった
import random  #Import random module

#Used for numeric assignment and new list generation
random.randint(Number of starts,Number of ends)  #Any integer value from start to end
random.uniform(Number of starts,Number of ends)  #Any floating point value from start to end
random.choice(list)  # listの中のどれかをピックアップしてくる
random.sample(list,Number of indexes) # シャッフルし新規list生成。

#Make changes to the randomly generated original list itself
random.shuffle([list])  # 上記と異なり元listそれ自体をシャッフル。
from datetime import datetime  #Up to seconds
from datetime import date #Until the day
from datetime import timedelta  #Call when also performing difference calculation
print(datetime.now())

datetime.now()  # 2019-01-10 13:16:48.904193 -now
datetime.year  # 2019 - %Y (corresponding format symbol)
datetime.month  # 01 - %m (corresponding format symbol)
datetime.day  # 10 - %d (corresponding format symbol)
datetime.hour  # 13 - %H (corresponding format symbol)
datetime.minute  # 16 - %M (corresponding format symbol)
datetime.second  # 48 - %S (corresponding format symbol)
datetime.date()  # 2019-01-10
datetime.time()  # 13:16:48.904193
datetime.datetime()  # 2019-01-10 13:16:48.904193

date.today()  # 2019-01-10 -now

#Get it as a time element if you add parentheses at the end, or as a character string if you do not add parentheses.

timedelta(days=3) 

#Show the difference. before+Or-By adding, you can add or subtract the intervals in parentheses.
# ()If there are only numbers inside, days=It will be calculated in, but it is kind to write it every time.

f'{formula= :Format}'  #You can make a formula with this. The format is specified by the format characters.
f'{formula:Format}'  #Conversion from date and time to string
datetime.strptime(formula,"書formula")  #Conversion from string to date and time

x = datetime(Year,Month,Day,Time,Minutes,Seconds)  # これで任意のDay付定義が可能。

Recommended Posts

PyQ ~ Python First Steps ~
First time python
First Python 3 ~ First comparison ~
First time python
First Python ~ Coding 2 ~
First python [O'REILLY]
PyQ ~ Python Beginner ~
First steps to try Google CloudVision in Python
First Python 3rd Edition
First Python image processing
[Python] Python / Scikit-learn's first SVM
First Python miscellaneous notes
[Python] Chapter 01-01 About Python (First Python)
[Cloud102] # 1 Get Started with Python (Part 1 Python First Steps)
First Fabric (Python deployment tool)
First neuron simulation with NEURON + Python
[Python / PyQ] 4. list, for statement
First simple regression analysis in Python
Python
First Python 3 ~ The beginning of repetition ~
Web scraping with Python First step
First Python 3 ~ Extra: Numerical Random Fantasy ~
[GUI with Python] PyQt5-The first step-
Prepare your first Python development environment
Python (from first time to execution)
C / C ++ programmer challenges Python (first step)
See python for the first time
Steps to install python3 on mac
The first step in Python Matplotlib
Continuously play the first Python Sukusta MV
First Steps for Machine Learning (AI) Beginners
Steps to install Python environment on Ubuntu
[Python] First data analysis / machine learning (Kaggle)
MongoDB for the first time in Python
"First Elasticsearch" starting with a python client
Python environment preparation (venv first time use)
Python standard library: First half (Python learning memo ⑧)