[Super basics of Python] I learned the basics of the basics, so I summarized it briefly.

Overview

I learned a little about Python, so I will summarize it briefly.

I don't know because it's a memo for myself.

table of contents

print

You can use print to print characters to the console.

example.py


print('Hello World')
#Output result-> Hello World

Write the character you want to output in ().

String output

The ** string ** is the character Hello World in the upper part.

The string must be enclosed in ', " . There is no difference in output regardless of which one is used.

example.py


#When enclosed in single quotes
print('Hello World')
#Output result-> Hello World

#When enclosed in double quotes
print("Hello World")
#Output result-> Hello World

Numerical output

You can handle ** numbers ** as well as strings.

If you want to output a number, ** you don't need to enclose it in quotation marks **.

If enclosed in quotation marks, it will be output as a character string.

example.py


#Output numbers as numbers
print(14)
#Output result->14 (numerical value)

#Output numbers as strings
print('7')
#Output result->7 (character string)

Addendum I have pointed out that I will correct it.

The print function calls the str function to convert the given argument into a string, and prints the result without quotes. Quote: * See comment section of this article *

In other words, all the values output by print are string type. I did not know at all.

Numerical calculation

Numerical values can be added or subtracted using + and -. As a caveat, ** all numbers and symbols must be written in half-width characters **.

Let's suppress the calculation symbols.

symbol processing
+ addition
- subtraction
* Multiplication
/ division
% Show the remainder of the division

example.py


#addition
print(5 + 3)
#Output result-> 8

#subtraction
print(10 - 8)
#Output result-> 2

#Multiplication
print(2 * 5)
#Output result-> 10

#division
print(6 / 2)
#Output result-> 3

#Calculating the remainder
print(10 % 3)
#Output result-> 1

Strings and numbers

When outputting the calculation result, you must be careful about the presence or absence of quotation marks.

example.py


print(2 + 4)
#Output result-> 6

print('2 + 4')
#Output result-> 2 + 4

If not enclosed in quotation marks, the calculation result will be output. On the other hand, when enclosed in quotation marks, 2 + 4 is interpreted as a character string and output as it is.

variable

Data can be assigned to ** variables **.

Variables are defined with variable name = value. Variable names do not need to be enclosed in ' or " .

In Python, = means assigning the right side to the left side.

There are a few things to keep in mind when naming variables.

--Variable names cannot start with numbers --When using variable names of two or more words, separate them with _

example.py


#String assignment
name = 'Fukumoto Taichi'

#Numerical substitution
age = 22

#When the variable name is 2 or more words
first_name = 'Taichi'

In the above example, Taichi is assigned to name and 22 is assigned to age`.

Now let's retrieve the variables defined in the above example.

When printing a value using a variable name, use print (variable name). Variable names do not have to be enclosed in '.

example.py


name = 'Fukumoto Taichi'

#Variable output
print(name)
#Output result->Fukumoto Taichi

In this way, the value assigned to the variable is output.

By using variables, it becomes clear what the contents of the data you are dealing with represent. This makes the code easier to read. It also has the advantage that the same data can be used repeatedly, and there are few corrections when making corrections such as numerical values.

The value of the variable can be updated. You can override the value of a variable by doing variable name = new value.

example.py


age = 22
print(age)
#Output result-> 22

#Update age value
age = 30
print(age)
#Output result-> 30

You can also update the value by adding or subtracting a number that has already been defined.

example.py


age = 22
print(age)
#Output result-> 22

age = age + 8
print(age)
#Output result-> 30

There are abbreviations when updating numbers. The abbreviations are summarized below.

standard Abbreviation
x = x + 1 x += 1
x = x – 1 x -= 1
x = x * 1 x *= 1
x = x / 1 x /= 1
x = x %1 x %= 1

Data type

There are different types of data to handle.

Here you will learn "** string type " and " numeric type **".

What was displayed by enclosing it in ' is ** character string type **.

On the other hand, numbers such as 2 and 14 are called ** numeric type **.

example.py


print(100)
#Output result-> 100

print('100')
#Output result-> 100

The result of the output is not visible, but the first is a numeric type and the second is a character string type.

String concatenation

From here, we will learn about string concatenation.

You can concatenate strings by using +.

example.py


first_name = 'Taichi'
last_name = 'Fukumoto'

#Concatenate character strings and output
print('My full name is' + last_name + first_name + 'is')
#Output result->My full name is Taichi Fukumoto

By writing as in the above example, you can concatenate strings, strings and variables, or a combination of variables.

One thing to note here is that ** variables must be of type string **.

In other words, ** can only be concatenated with the same data type **.

Let's look at the following example.

example.py


print(3 + 7)
#Output result-> 10

print('3' + '7')
#Output result-> 37

print('3' + 7)
#Output result-> Type Error

Since the code on the first line is written in numeric type, the result of the calculation formula is output. Since the code on the second line is written in the character string type, 37, which is a concatenation of the character string 3 and the character string 7, is output. Since the code on the third line uses the character string type and the numeric column type, an error has occurred.

I learned that concatenation can only be done between string types.

Type conversion

Numerical type → Character string type

So how do you concatenate variables that have been assigned a numeric type as a string?

example.py


name = 'Taichi'
age = 22

Learn how to use these variables to output Taichi is 22 years old.

Type conversion is performed when concatenating numeric variables as a character string.

Use str to convert a numeric type to a string type. You can convert to a numeric type by using str (numeric type).

example.py


name = 'Taichi'
age = 22

print(name + 'Is' + str(age) + 'I'm old.')
#Output result->Taichi is 22 years old

The variable age was converted to a string type by str, so the output was done without error.

Character string type → Numerical type

Contrary to the previous example, use int to convert a string type to a numeric type. Like str, you can convert it to a numeric type by usingint (string type).

Let's look at an example.

example.py


count = '5'
price = 200

total_price = price * int(count)

print(total_price)
#Output result-> 1000

Since 5 is assigned as a character string type to count, the process is executed without causing an error by converting it to a numeric type and calculating it.

Conditional branch

We will learn about conditional branching, which processes only when a certain condition is met.

Before learning the conditional branching syntax, let's learn about "** boolean " and " comparison operator **".

Boolean value

First, we will learn about ** truth value **.

Execute code similar to the following.

example.py


age = 20
print(age == 20)
#Output result-> True

== is a comparison operator that compares whether both sides are equal. The comparison operators are explained together.

So what exactly is the True output at this time?

This True is what is called a boolean value. Data types that handle false values are classified as "** false value type **", and there are two types, True and False. If the conditional expression part using the comparison operator holds, it becomes True, and if it does not hold, it becomes False.

Comparison operator

Let's take a look at the "** comparison operator **" that came out earlier.

The ** comparison operator ** is a symbol ** used to compare the equality and magnitude of values **.

The following comparison operators exist.

operator meaning
a == b True when a is equal to b
a != b True when a is not equal to b
a > b True when a is greater than b
a < b True when a is less than b
a >= b True when a is greater than or equal to b
a <= b True when a is less than or equal to b

This comparison operator appears in the conditional statement at the time of conditional branching, so be sure to suppress it.

if statement

Now let's look at the conditional branching code.

By using ** if **, it is possible to perform processing only under certain conditions **.

Let's look at the syntax.

if conditional expression:
processing

Specify the conditional expression after the if, and write the process to be executed when the condition is satisfied on the next line. Please note that ** processing must be indented **.

Let's look at an example.

example.py


age = 22

if age >= 20:
    print('You can drink alcohol')

#Output result->You can drink alcohol

In the above example, the part of age> = 20 is the conditional expression.

In the above conditional expression, "** If the value of age is 20 or more **" becomes True.

Since 22 is assigned to age and the conditional expression becomes True, the subsequent processingprint ('you can drink alcohol')is executed. Let's look at the following example.

example.py


age = 19

if age >= 20:
print('You can drink alcohol')

#Output result->You can drink alcohol

In the above example, there is no indent in the processing part. As a result, processing that should not have been executed has been performed.

Watch out for indentation.

else

By combining ** else ** with the if statement, you can" perform another process ** if the conditions of the ** if statement are not met ** ".

The syntax is as follows:

if conditional expression:
processing
else:
processing

After the if process, writeelse:and write the process on the next line. Don't forget you need : after else. Also, pay attention to the indentation as well as the if statement.

Let's look at a concrete example.

example.py


age = 19

if age >= 20:
    print('You can drink alcohol')

else:
    print('Alcohol has been around since I was 20 years old')

#Output result->Alcohol has been around since I was 20 years old

In the concrete example, 19 is assigned to age, so the condition of the if block is not satisfied.

Therefore, the process described in else is executed.

elif

If you want to define multiple ** conditional expressions that do not hold in the if statement **, use ** elif **. The syntax is as follows:

if conditional expression:
processing
elif conditional expression:
processing
else:
processing

Add a elif block between the if and the else. The writing method is the same as for if, writeconditional expression:after` elif', and write the process on the next line.

You can write as many elifs as you like. However, ** it is judged from the top whether the conditions are satisfied, and only the part that meets the conditions is processed first **.

When writing conditions using elif, you need to pay attention to the order of the conditions.

Let's look at a concrete example.

example.py


number = 0

if number > 0:
    print('Is positive')

elif number == 0:
    print('0')

else:
    print('Negative')

#Output result->0

Since 0 is assigned to number, the condition of elif, number == 0, is satisfied.

Therefore, the process described in elif is executed.

Since the processing of elif has been executed, the processing ends here.

Combination of conditions

and

By combining multiple conditional expressions using and, you can execute the process when" ** Condition 1 and Condition 2 are satisfied ** ".

if conditional expression 1 and conditional expression 2:
processing

When and is used, when all conditional expressions are True, the whole becomes True and the process is executed.

or

By combining multiple conditional expressions using or, you can execute the process when" ** Either condition 1 or condition 2 is satisfied ** ".

if conditional expression 1 or conditional expression 2:
processing

When or is used, if even one of multiple conditional expressions is True, the whole becomes True and the process is executed.

not

You can use not to negate a ** condition **.

The process is executed when the conditional expression is not True. In other words, if you do something like not conditional expression, ** if the conditional expression is True, the whole will be False **.

if not conditional expression:
processing

list

Use "** list **" to handle multiple data.

Lists are created using [], such as [〇〇, △△,…]. Each value in the list is called a "** element **".

Also, since the list is also a single value, it can be assigned to a ** variable **.

example.py


names = ['Yamada', 'Tanaka', 'Suzuki']

print(names)
#Output result-> ['Yamada', 'Tanaka', 'Suzuki']

When you output, the list is output as it is. Also, it is common to use the plural form for variables.

The elements of the list are numbered "** 0, 1, 2, ... " in order from the front. This is called " index number **".

In the above example, 'Yamada' is the element with index number 0.

Each element of the list can be obtained by using the list list name [index number].

example.py


names = ['Yamada', 'Tanaka', 'Suzuki']

print('He' + names[0] + 'Mr. is.')
#Output result->He is Mr. Yamada.

In names [0], the element with the index number 0 of the element is fetched, so Yamada is entered.

Update list elements

You can update the elements of the list by setting ** list [index number] = value **.

It's like specifying the location you want to update and reassigning.

Let's look at a concrete example.

example.py


names = ['Yamada', 'Tanaka', 'Suzuki']
names[2] = 'Sato'

print(names)
#Output result-> ['Yamada', 'Tanaka', 'Sato']

Updating the element with index number 2. You can see that the values have been updated in the output list.

Add list elements

Next, let's add a value to the list.

** It is possible to add a new element to the already defined list ** by setting list.append (value) **.

Let's look at a concrete example.

example.py


names = ['Yamada', 'Tanaka', 'Suzuki']
names.append('Sato')

print(names)
#Output result-> ['Yamada', 'Tanaka', 'Suzuki', 'Sato']

The element is added to the ** end of the list **.

Even in the concrete example, you can see that the list with Sato added to the end of the list is output.

dictionary

"** Dictionary **" is also used to manage multiple data together.

Dictionaries, unlike lists, manage index numbers by giving them a name called "** key **" instead.

The dictionary is defined as ** {key 1: value 1, key 2: value 2,…} **.

Generally, a character string is used for the key.

example.py


names = {'Yamada': 22, 'Tanaka': 40, 'Suzuki': 33}

print(names)
#Output result-> {'Yamada': 22, 'Tanaka': 40, 'Suzuki': 33}

Since the elements of the dictionary have no order, the order of the elements may be different from what you defined when you output.

The elements of the dictionary can be retrieved by using the key you want to retrieve and using the dictionary name ['key'].

example.py


names = {'Yamada': 22, 'Tanaka': 40, 'Suzuki': 33}

print('He' + str(names['Tanaka']) + 'I'm old.')
#Output result->He is 40 years old

Update dictionary elements

It's basically the same as updating the list.

Use ** key ** instead of index number.

example.py


names = {'Yamada': 22, 'Tanaka': 40, 'Suzuki': 33}

#Update value
names['Tanaka'] = 50

print('He' + str(names['Tanaka']) + 'I'm old.')
#Output result->He is 50 years old

I was able to confirm that the value was updated.

Add dictionary elements

When adding an element to a dictionary, set a new key and assign a value to it, such as dictionary name ['new key'] = value.

example.py


names = {'Yamada': 22, 'Tanaka': 40, 'Suzuki': 33}
names['Sato'] = 15

#Output dictionary
print(names)
#Output result-> {'Yamada': 22, 'Tanaka': 40, 'Suzuki': 33, 'Sato': 15}

#Output newly added elements
print('He' + str(names['Sato']) + 'I'm old.')
#Output result->He is 15 years old

Elements have been added and can be specified and retrieved.

Iterative processing

You will learn about "** for statement " and " while statement **", which are Python iterations.

for statement

If you want to retrieve all the elements of a list one by one, specifying the index numbers one by one can be very tedious.

By using "** for statement ", you can perform " iterative processing **".

The for statement is described as ** for variable name in list name: **.

The elements of the list are entered in the variable name one by one from the beginning, and then the processing in the for statement is executed.

Let's look at a concrete example.

example.py


names = ['Yamada', 'Tanaka', 'Suzuki']

for name in names:
    print('He' + name + 'Mr. is.')

#Output result->
He is Mr. Yamada.
He is Mr. Tanaka.
He is Mr. Suzuki.

In this way, the output processing in the for statement is performed in order from the top of the list. Also, variable names are generally in the singular form of list names.

Similarly, by using the for statement in the dictionary, you can retrieve the elements one by one and execute the iterative process.

In the case of a dictionary, the for statement is described as ** for 〇〇_key in dictionary name: **.

Let's look at a concrete example.

example.py


names = {'Yamada': 22, 'Tanaka': 40, 'Suzuki': 33}

for name_key in names:
    print(name_key + 'Is' + str(names[name_key]) + 'I'm old.')

#Output result->
Mr. Yamada is 22 years old.
Mr. Tanaka is 40 years old.
Suzuki is 33 years old.

In this way, the elements of the dictionary could also be retrieved with the for statement.

while statement

Another iterative process is the "** while statement **".

You can use the while statement to "** repeat the process while a certain condition is met **".

Let's look at the syntax.

example.py


while conditional expression:
Processing including value update

Write as while conditional expression:, then indent and write the process. The processing part always includes the processing to update the value.

Let's look at a concrete example.

example.py


x = 1

while x <= 5:
    print(x)
    x += 1
#Output result->
1
2
3
4
5

Looking at the example, the conditional expression part is "** when ** x is 5 or less ". The processing in the while statement is " x value ** output " and then " x plus 1 **".

After 5 is output, 1 is added, the value of x becomes 6, and the condition is not satisfied, so the process ends.

Therefore, the process is repeated until x becomes 5.

infinite loop

In the while statement, if you forget to update the value of the variable at the end of the process, or if the indentation is incorrect, the conditional expression will always be True, and ** it will be repeated indefinitely **.

be careful.

break and continue

break

By using break, it is possible to" ** force termination ** "of the iterative process.

break is used in combination with conditional branches such as if statements.

Let's look at a concrete example.

example.py


numbers = [1, 2, 3, 4, 5]

for number in numbers:
    print(number)
    if number == 4:
        break

#Output result->
1
2
3
4

Let's take a look at the code.

The conditional expression of the if statement is "when it becomes 4". If break is written in the if block and the condition is met, it will be executed.

Therefore, the processing is completed without outputting 5.

continue

You can use ** continue ** to skip processing if ** conditions are met **.

It is used in combination with conditional branching like break.

example.py


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for number in numbers:
    if number % 2 == 0:
        continue
    print(number)

#Output result->
1
3
5
7
9

Since the conditional expression part of if is" ** when number is divisible by 2 ** ", ** even processing is skipped and only odd numbers are output **.

Summary

I tried to summarize at once. The code in Python is simple and easy to read.

Thank you for reading until the end.

Recommended Posts

[Super basics of Python] I learned the basics of the basics, so I summarized it briefly.
I didn't know the basics of Python
[Example of Python improvement] I learned the basics of Python on a free site in 2 weeks.
I passed the Python data analysis test, so I summarized the points
What beginners learned from the basics of variables in python
Review of the basics of Python (FizzBuzz)
About the basics list of Python basics
Learn the basics of Python ① Beginners
I made a function to crop the image of python openCV, so please use it.
[Python3] Understand the basics of Beautiful Soup
I summarized the folder structure of Flask
The basics of running NoxPlayer in Python
[Python] I personally summarized the basic grammar.
The Python project template I think of.
I studied about Linux, so I summarized it.
[Python3] Understand the basics of file operations
I didn't understand the behavior of numpy's argsort, so I will summarize it.
Extraction of synonyms using Word2Vec went well, so I summarized the analysis
Basics of Python ①
Basics of python ①
Try the free version of Progate [Python I]
I touched some of the new features of Python 3.8 ①
I didn't understand the Resize of TensorFlow so I tried to summarize it visually.
[Trainer's Recipe] I touched the flame of the Python framework.
Basics of I / O screen using tkinter in python3
The math of some entrance exam question is awkward to think about, so I left it to python after all
Since memory_profiler of python is heavy, I measured it
Basics of Python scraping basics
Let's break down the basics of TensorFlow Python code
the zen of Python
The concept of reference in Python collapsed for a moment, so I experimented a little.
I checked out the versions of Blender and Python
I want to fully understand the basics of Bokeh
# 4 [python] Basics of functions
AWS Lambda now supports Python so I tried it
Basics of python: Output
How much do you know the basics of Python?
I tried to summarize the string operations of Python
I learned the basics of reinforcement learning and played with Cart Pole (implementing simple Q Learning)
I tried to find the entropy of the image with python
I tried "gamma correction" of the image with Python + OpenCV
I tried the accuracy of three Stirling's approximations in python
I evaluated the strategy of stock system trading with Python.
What I learned by solving 30 questions of python Project Euler
[Python] I installed the game from pip and played it
[Python] I tried to visualize the follow relationship of Twitter
The process of making Python code object-oriented and improving it
I want to know the features of Python and pip
[Python] I tried collecting data using the API of wikipedia
I want to know the legend of the IT technology world
[Python] Tensorflow 2.0 did not support Python 3.8, so the story of downgrading Python
Towards the retirement of Python2
About the ease of Python
python: Basics of using scikit-learn ①
What I learned in Python
I learned Python basic grammar
About the features of Python
Basics of Python × GIS (Part 1)
I downloaded the python source
The Power of Pandas: Python
I couldn't understand Fence Repair of the ant book easily, so I will follow it in detail.