[Python] I personally summarized the basic grammar.

I will summarize Python to deepen my understanding. I will update it from time to time.

References ☆ Daigo Kunimoto / Akiyoshi Sudo "Introduction to Python for a refreshing understanding"

flow

① Creation of source code

The extension of the source file is " .py "

② Execution

-By Python interpreter (: software) Convert source code to machine language (: computer-understandable language) -If there is a grammatical error, SyntaxError is displayed. -Execution is canceled at the time of Exception (: error at runtime)

formula

[Arithmetic operator]

//: The quotient of division (the answer is an integer) **: Exponentiation *: String iteration (string * number or number * string)

[Priority] High: ** Medium: *, /, % Low: +, -

print(1 + 1 * 7)   --8

print ((1 + 1) * 7) --14, parentheses can be used to increase priority

[Escape sequence]

print ('Good morning \ n you guys \') print ('\ "and '')

Special symbols used when using string literals

\ n: Line break \\: Backslash \': Single quote \" : Double quotes

variable

Variable name = value # variable assignment Variable name #variable reference

print ('The diameter of a circle with a radius of 7 is') ans = 7 * 2 --assignment print (ans) --See print ('circumference') print(ans * 3.14)

name, age ='John', 33 --Unpacked assignment (: How to define multiple variables together)

【Reserved word】
import keyword
print(keyword.kwlist)

-A word that cannot be used as a identifier (: a sequence of letters and numbers used in a name) ・ You can check with the above code ・ When you want to fix the contents, you often name it with capital letters.

[Composite assignment operator]

age + = 1-Same as "age = age + 1" price * = 1.1-Same as "price = price * 1.1"

[Input function]

Variable name = input (string)

name = input ('Tell me your name!') print ('Welcome!' + Name)

Assign keyboard input to variables Data type is str type

Data type

[Main list] int: integer float: decimal str: string bool: Boolean value

[conversion] int function: Truncate decimals, string will result in error float function: String will result in error str function bool function

・ Only character strings or numerical values can be concatenated. -Python does not have implicit type conversion (: mechanism for automatic type conversion), so Must do explicit type conversion`

[Type function]

type (variable name) int (variable name) float (variable name) str (variable name) bool (variable name)

x = 3.14

y = int (x) --int function print(y) print (type (y)) --type function z = str (x) --str function print(z) print(type(z)) print(z * 2)

Variables do not have a data type (= any data type value can be assigned) ➡︎ Find out which data type is stored

[Format function]

'String containing {}'. format (value 1, value 2 ...)

name ='God' age = 77 where print ('my name is {}, year is {}') .format (name, age)-{} embeds the value

You can embed a value in a string {} = Placeholder

[F-string function]

print (f'My name is {name}, year is {age}')

Features introduced in Python 3.6 It is possible to directly specify the variable name (expression is also OK) in the placeholder

Collection (or container)

A mechanism for grouping related data and treating it as a single variable

❶ [List (or array)]

Variable name = [Element 1, Element 2 ...] #Definition List [subscript] # reference List [changed value subscript] = changed value #change

members = ['Sato',' Tanaka','Suzuki'] members [0] ='Kobayashi'-"Sato" is changed to "Kobayashi" print(members) print(members[0])

[Purpose of use] Combine multiple data with order intoone

[Sum function]

sum (list)

scores = [70, 80, 90]
total = sum(scores)

print ('The total is {} points.'. Format (total))

-Calculate the total value of list elements -Cannot be used in the list that contains the string ・ Can also be used for tuples and sets

[Len function]

len (list)

scores = [70, 80, 90]
avg = total / len(scores)

print ('The average is {} points.'. Format (avg))

-Calculate the mean of list elements ・ Can also be used for dictionary, tuple, and set

[Append function]

List .append (append value)

members.append('Charotte')

Add to the end of the list element

[Remove function]

List .remove

members.remove('Charotte')

Delete the specified value from the list element

[Slice sentence]

List variable [A: B] #Refer to the element of subscript A or more and less than B List variable [-A] # Reference (Negative number specified)

scores = [70, 80, 90, 100]
print(scores[0:2])  --70,80
print(scores[1:])   --80,90,100
print(scores[:3])   --70,80,90
print(scores[:])    --70,80,90,100
print(scores[-3])   --80

You can specify the range of list elements A: ➡︎ Elements above subscript A : B➡︎ Elements less than subscript B : ➡︎ All elements -A➡︎ Count from the end of the list ("1"at the beginning of counting)

❷ [Dictionary (or map)]

Variable name = {Key 1: Value 1, Key 2: Value 2 ...} #Definition Dictionary name [key name] # reference Dictionary name [additional key name] = additional value #addition Dictionary name [change key name] = changed value #change

scores = {'Japanese Language':70, 'Mathmatics':80, 'Science':90, 'Social Studies':100} 
scores['English'] = 88
scores['Science'] = 98
print(scores['Social Studies']) 

[Purpose of use] Manage multiple data with key ➡︎ Ordering added from Python 3.7

-- No data type specified Duplicate keys are possible (not recommended) Keys are case sensitive

[Del sentence]

del Dictionary name [key name to delete]

del scores['Mathmatics']

Delete the dictionary element

[Values method]

Dictionary name.values ()

total = sum(scores.values())
print(total)

Calculate the total value of dictionary elements

❸ [Tuple]

Variable name = (value 1, value 2 ...)

points = (1, 2, 3) 
print(points)

members = ('James',) --Tuple with only one element (with a comma after the value) print(type(members))

Has characteristics similar to lists (however, elements cannot be added, changed, or deleted) Collectively referred to as sequence with the list

[Purpose of use] Unable to rewrite Combine multiple data into one

❹ [Set (or set)]

Variable name = {value 1, value 2 ...}

numbers = {10, 20, 30, 30}
print(numbers)

It also has similar characteristics to lists (but not duplicate, no subscripts & keys, no order)

[Purpose of use] Manage type as data

[Add function]

Set .add (additional value)

scores.add(100);

Used in place of append function in set Also, the set has a tailless element, so it's just added.

Mutual conversion

list function: Convert to list * In the case oflist (), an empty collection is created tuple function: Convert to tuple set function: Convert to a set

scores = {'Japanese Language':70, 'Mathmatics':80, 'Science':90, 'Social Studies':100}
members = ['John', 'Mike', 'Jack']

print (tuple (members)) --Convert members to tuples print (list (scores)) --Convert scores to list print (set (scores.values ())) --Convert scores to a set

dict (zip (list of keys, list of values)) #Convert to dictionary

Nest

a_scores = {'Japanese Language':70, 'Mathmatics':80, 'Science':90, 'Social Studies':100}
b_scores = {'Japanese Language':100, 'Mathmatics':90, 'Science':80, 'Social Studies':70}
member_scores = {
  'A' = a_scores,
  'B' = b_scores,
}
--
member_likes = {

'C': {'Cat','Strawberry'}, 'D': {'Dog','Mikan'} } print (member_likes) --Show everyone's likes print (member_likes ['C']) --Display C likes -- x = [1, 2, 3] y = [11, 22, 33] z = [a, b] --A two-dimensional list with a as 0th and b as 1st (: structure that incorporates another list in the list) print (z) --z See whole print (z [0]) --see list x in z print (z [1] [2]) --See list y in z

Set arithmetic

Set 1 & Set 2

member_likes = {

'E': {'Baseball',' Meat'}, 'F': {'Fish',' Baseball'} } common_likes = member_likes['E'] & member_likes['F']
print(common_likes)

Features of set only Find the commons and differences of two sets

[Set operator] | Operator: Union -Operator: Difference set & operator: intersection ^ Operator: Symmetric difference

G = {1, 2, 3, 4}
H = {2, 3, 4, 5}
print(G | H)    --1,2,3,4,5
print(G - H)    --1
print(G & H)    --2,3,4
print(G ^ H)    --1,5

Conditional branch

Control structure: A program structure that manages the execution order of statements (: execution unit for each line) Structured theorem: A program is made up of a combination of control structures sequential, branch, and iteration.

name ='Yoshiko'; print ('My name is not {}.'. Format (name))-You can write multiple sentences on one line by adding a semicolon at the end of the line.

[If-else statement]

if conditional expression: --Be careful not to forget the colon if block else: --Be careful not to forget the colon else block

name = input ('Tell me your name >>') print ('{}, nice to meet you.'. Format (name)) food = input (What is'{}'s favorite food? >>'.format (name)) if food =='cake': print ('It's delicious!') else:                           print ('{} is also good.'. Format (food))

【pass】 if conditional expression: Processing content else: pass--Since empty blocks are not possible in Python, empty blocks can be allowed by "pass"

[In operator]

if'cake' in food: Include any "cake" in --food -- scores = [70, 80, 90, 100] if 100 in scores: --Check if there is "100" in scores -- -- Key name in dictionary name

scores = {'Japanese Language':70, 'Mathmatics':80, 'Science':90, 'Social Studies':100}

key = input ('Please enter the subject name to be added.') if key in scores: --scores to see if there is a key

[Logical operator]

and: and or: or not: Otherwise

if score> = 70 and score <= 100: --70 or more and 100 or less if 70 <= score <= 100: --This way of writing is also possible (but not possible except for Python)

if score <70 or score> 100: --less than 70 or greater than 100 if not (score <70 and score> 100): must be less than --70 and above 100 if not'cake'in food: --if food does not contain "cake"

[If-elif statement]

if conditional expression 1: if block elif conditional expression 2: elif block (Else: #can be omitted else block)

score = int (input ('Please enter your score')) if score < 0 or score > 100: print ('Incorrect input. Please re-enter correctly') elif score >= 70: print ('Pass. Congratulations.') else: print ('Failed. Have a follow-up exam.')

[Nest]

print ('Please answer the question with yes or no.') money = input ('Do you have any money?') if money == 'yes': tight_eat = input ('Do you want to eat a lot?') light_eat = input ('Do you want to eat lightly?')

    if tight_eat == 'yes':

print ('How about ramen?') elif light_eat == 'yes': print ('How about a sandwich?') else: print ('Let's eat at home.')

Recommended Posts

[Python] I personally summarized the basic grammar.
I learned Python basic grammar
Python3 basic grammar
I wrote the basic grammar of Python with Jupyter Lab
Python basic grammar / algorithm
Python basic grammar (miscellaneous)
Python basic grammar note (4)
Python basic grammar note (3)
Python basic grammar memo
Basic Python 3 grammar (some Python iterations)
Python installation and basic grammar
Python Basic Grammar Memo (Part 1)
Python basic grammar (miscellaneous) Memo (3)
Python basic grammar (miscellaneous) Memo (2)
Basic Python grammar for beginners
Python basic grammar (miscellaneous) Memo (4)
Python (Python 3.7.7) installation and basic grammar
I downloaded the python source
I passed the Python data analysis test, so I summarized the points
Java and Python basic grammar comparison
I liked the tweet with python. ..
Basic grammar of Python3 system (dictionary)
I wrote the queue in Python
I wrote the stack in Python
A pharmaceutical company researcher summarized the basic description rules of Python
[Super basics of Python] I learned the basics of the basics, so I summarized it briefly.
I summarized the folder structure of Flask
[Basic grammar] Differences between Ruby / Python / PHP
Basic grammar of Python3 system (character string)
Python: I tried the traveling salesman problem
Basic grammar of Python3 series (list, tuple)
The Python project template I think of.
Python Basic Course (at the end of 15)
[Python beginner] I collected the articles I wrote
I tried to touch Python (basic syntax)
Basic grammar of Python3 system (included notation)
Take the Python3 Engineer Certification Basic Exam
I tried the Python Tornado Testing Framework
Comparing the basic grammar of Python and Go in an easy-to-understand manner
I tried "smoothing" the image with Python + OpenCV
[Python] I tried substituting the function name for the function name
RF Python Basic_01
vprof --I tried using the profiler for Python
python grammar check
I tried "differentiating" the image with Python + OpenCV
I tried simulating the "birthday paradox" in Python
I tried the least squares method in Python
I started python
I tried python programming for the first time.
Basic Python writing
[Python] I searched for the longest Pokemon Shiritori
This is the only basic review of Python ~ 1 ~
This is the only basic review of Python ~ 2 ~
VBA user tried using Python / R: basic grammar
I tried using the Datetime module by Python
What you want to memorize with the basic "string manipulation" grammar of python
I touched some of the new features of Python 3.8 ①
I can't click the Selenium checkbox Python VBA
I implemented the inverse gamma function in python
This is the only basic review of Python ~ 3 ~
RF Python Basic_02