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"
The extension of the source file is " .py "
-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)
//
: 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
print ('Good morning \ n you guys \') print ('\ "and '')
Special symbols used when using string literals
\ n
: Line break
\\
: Backslash
\'
: Single quote
\"
: Double quotes
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)
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
.
age + = 1-Same as "age = age + 1" price * = 1.1-Same as "price = price * 1.1"
Variable name = input (string)
name = input ('Tell me your name!') print ('Welcome!' + Name)
Assign keyboard input to variables
Data type is str
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 (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
'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
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
A mechanism for grouping related data and treating it as a single variable
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 (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 tuple
s and sets
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
List .append (append value)
members.append('Charotte')
Add
to the end of the list element
List .remove
members.remove('Charotte')
Delete
the specified value from the list element
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)
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 Dictionary name [key name to delete]
del scores['Mathmatics']
Delete
the dictionary element
Dictionary name.values ()
total = sum(scores.values())
print(total)
Calculate the total value
of dictionary elements
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
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
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.
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
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 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
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 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"
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
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 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.')
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