[For those who have mastered other programming languages] 10 points to catch up on Python points

Overview Python is well known as a simple and easy-to-learn object-oriented language. For those who have mastered other languages, I have selected 10 unique elements of Python at my own discretion, so I will describe them.

1. No need for line break ";"

The common rule for many languages, "when line breaks;", is unnecessary in Python. However, since it is recognized as a line break, even if the following code is executed, no error will occur and the behavior will be the same as before.

>>> print("1"); print("2")
1
2

2. Indentation represents a block

In other languages, indentation was an element that improved the readability of the code and did not affect its behavior. However, Python uses indentation to represent blocks.

if x > 0:
  print("positive") #In the if statement
print("always")     #outside the if statement

In the above code, if x is 0 or more, both "positive" and "always" are displayed, and in other cases, "always" is output.

Also, if there is no appropriate indentation as shown below, ʻIndentationError: expected an indented block` will occur.

if x > 0:
print("positive")   #Indentation Error occurred

3. Single quotation and double quotation are synonymous

In Python, there is no difference between them. The following codes all behave in the same way.

>>> print('single')
single
>>> print("double")
double

If you put ' in the character string, the notation is different.

>>> print('It\'s single') # \Escape with
It's single

>>> print("It's double")  #Quotation marks in the string
It's double

Since it is not necessary to unify the notation within the same code, it is possible to set certain rules such as single for words and double for sentences.

s = 'single'
w = "It's a double!

4. Variable declaration and type

No need to specify var or type. You can store numbers, strings, and boolean values in the format variable name = value. However, since the type is inferred from the value, an initial value is required. All the following notations are errors.

#No type specification required
int a = 1
        ^
SyntaxError: invalid syntax


#No need to write var
var a = 1
        ^
SyntaxError: invalid syntax


#Error even if there is no initial value
a
NameError: name 'a' is not defined    

Also, a variable of a completely different type can be assigned to a variable once declared. In that case, the type of the variable changes at the same time.

>>> a = 100
>>> type(a)
<class 'int'>

>>> a = "text"
>>> type(a)
<class 'str'>

>>> a = True
>>> type(a)
<class 'bool'>

5. Other frequently used data types

In Python, in addition to numbers, strings, and booleans, there are ** lists, tuples, sets, and dictionary types **. Both are data types that store multiple data, and have the following features.

Data type name Feature How to declare
list(list) No restrictions on addition / duplication [val1, val2, ...]
Tuple(tuple) Do not allow additions / updates after declaration,High performance (val1, val2, ...)
set(set) Do not allow duplicates of equivalent values {val1, val2, ...}
Dictionary type(dict) key-value format {key1: val1, key2: val2, ...}
###List type
list1 = [1,2,3]
type(list1)    # -> <class 'list'>
print(list1)   # -> [1, 2, 3]
print(list1[0] # -> 0
list1.append(4)
print(list1)   # -> [1, 2, 3, 4]

###Set type
set1 = {1,2,3,3}
type(set1)  # -> <class 'set'>
print(set1) # -> {1, 2, 3}
set1[0] = 9 # -> TypeError: 'set' object does not support item assignment
set1.add(4)
print(set1) # -> {1, 2, 3, 4}

###Tuple type
tuple1 = (1,2,3)
type(tuple1)  # -> <class 'tuple'>
print(tuple1) # -> (1,2,3,3)
tuple1[0] = 9 # -> TypeError: 'tuple' object does not support item assignment

###Dictionary type
dict1 = {"a": 123, "b": 456, "c": 789}
type(dict1)  # -> <class 'dict'>
print(dict1) # -> {'a': 123, 'b': 456, 'c': 789}
dict1["d"] = 0
print(dict1) # -> {'a': 123, 'b': 456, 'c': 789, 'd': 0}

Tuples are used when you do not want to change the values or order declared once, such as statistical values, or when you do not need to change them. It does not overwhelm the memory, which improves performance.

Also, these can be converted to each other. However, an error may occur depending on the configuration.

list1 = [1,2,3]
print(tuple(list1)) # -> (1, 2, 3)
print(set(list1))   # -> {1, 2, 3}
list2 = [["a", 123], ["b", 456], ["c", 789]]
print(dict(list2))  # -> {'a': 123, 'b': 456, 'c': 789}

6. Slice operation

As with the previous data type, in Python, a data type that can handle multiple elements such as "arrays" in a single variable is called ** sequence type **. Specifically, the following applies.

Mold Interpretation
String(string) Consecutive characters
range(range) Consecutive numbers
Part-Time Job(bytes) Consecutive bytes
list(list) Continuous data,Can handle any data
Tuple(tuple) Continuous data that cannot be added / updated
set(set) Contiguous data that does not allow duplication

For these, a ** slice operation ** that cuts a part and returns a copy is available in Python. When specifying, specify as seq [start: stop: step]. If no value is specified, the default value will be applied, but all cannot be unspecified.

argument Value to specify Default
start Cut-out viewpoint index 0
end Cut end point index Value equal to the number of elements
step Number of steps when cutting
In case of negative number, reverse order
1

The index is easy to understand the idea of Python Tutorial. In other words, "** index points to the boundary between elements, and the left end of the first element is 0 **". In addition, the negative value of the negatively specified index increases every time the index pointing to the last character returns to the previous -1, or later.

 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1

Based on the above, use as follows.

str = "Python"
print(str[3:])   # -> "hon"
print(str[:3] )  # -> "Pyt"
print(str[::-1]) # -> "nohtyP"
print(str[::2])  # -> "Pto"

6. Points to note regarding control statements in general

The overall points to keep in mind are as follows.

--No () is required in conditional expressions --Enter : at the end

For example, how to use the if statement is as follows. There is no big difference compared to other languages, but only the notation of ʻelif` may be a little special.

###if statement
if x > 0:
  print("positive")
elif x < 0:
  print("negative")
else:
  print("zero")

7. The for statement can be flexibly turned in combination with the sequence.

Below in, the element can be turned by specifying the sequence type described above.

list1 = [1,2,3]
for val in list1:
  print(val)

1
2
3

If you haven't used a sequence type variable in advance, it's convenient because you can generate a sequence of consecutive numbers with the range function.


#Starts at 0 with one argument
for i in range(3):
  print(i)

0
1
2

#You can change the start point with two arguments
for i in range(1, 4):
  print(i)

1
2
3

#Interval can be changed with 3 arguments
for i in range(1, 8, 2): 
  print(i)

1
3
5
7

8. Processing with termination can be simplified with with statement

** with ** exists in the characteristic syntax of Python. Generally, when performing "file reading / writing" or "communication processing" in another language, it was necessary to clearly declare the start and end. However, in Python, by declaring the start process at the same time as the with statement, the end process is automatically performed when the indent is removed.

Here, read / write a file is taken as an example.

#Read file
with open("read.txt", "r") as file1:
    print(file1.read())

#Writing a file
with open("write.txt", "w") as file2:
    print(file2.write())

Of course, it is also possible to declare by nesting as follows.

#Write the contents read from the file to another file
with open("reaad.txt", "r") as file1:
    with open("write.txt", "w") as file2:
        file2.write(file1.read())

9. You can create a function that returns multiple values

First, the function definition in python is done using def as follows.

def double(x):
  return x * x

print(double(10)) # -> 100

At this time, multiple return values can be specified by tuples or commas. Comma delimiters are possible because in Python, comma-separated values are considered tuples without parentheses. At this time, it is also possible to store these multiple return values in different variables.

def test():
  return "a", 123, True # return ("a", 123, True)Synonymous with

print(test())           # -> ('a', 123, True)

a, b, c = test()
print(a)                # -> 'a'
print(b)                # -> 123               
 print(c)                # -> True

10. Use of the library is import

In addition to the built-in functions that are available by default, Python can easily use various libraries by executing ʻimport` as appropriate. In PEP8, it is desirable to declare the import declaration at the beginning of the program and describe it in the following order.

  1. Standard library
  2. Third party library
  3. Local library (self-made library) In many cases, the groups are separated by blank lines, and the same group is in alphabetical order.
#Standard library
import math
import os
import sys

#Third party library
import Requests

#Homebrew library
import my_package1
import my_package2

Also, ʻasandfrom are often used along with ʻimport. By using as, you can give an alias to the imported module or object. For example, math is often m and numpy is np.

import math as m
import numpy as np

print(np,array([1,2], [100,200])) # -> array([[1, 2],[100, 200]])
print(m.pi)                       # -> 3.141592653589793

from is roughly divided into one of the following two types of usage. --from <module name> import <object name> --from <package name> import <module name> Here, considering that the library hierarchy has a structure of ** packages> modules> objects **, it is an image of acquiring the lower hierarchy from the upper hierarchy.

Roughly speaking

For example, if you often use pi, you can specify the object pi and import it.

from math import pi #Import pi object of math class
print(pi)           #It can be used as it is without specifying math.

At the end

If there are 10 items, it will be quite a lot, but if you can understand the contents here, it will be a Python beginner graduation first. After that, if you can grasp the usage unique to various general-purpose libraries as appropriate, you should be able to code smoothly!

Recommended Posts

[For those who have mastered other programming languages] 10 points to catch up on Python points
For those who are new to programming but have decided to analyze data with Python
I tried to teach Python to those who have no programming experience
Getting Started with Processing and p5.js (for those who have done other languages) 02
Getting Started with Processing and p5.js (for those who have done other languages) 01
Anxible points for those who want to introduce Ansible
For those who want to write Python with vim
For those who can't install Python on Windows XP
Python environment construction 2016 for those who aim to be data scientists
Python techniques for those who want to get rid of beginners
For those who don't have Keras or TensorFlow on GPU on macOS Sierra
To those who do not have her on Christmas Eve ◯ Voice keyboard
Introduced Mac (M1) TensorFlow (recommended for those who have installed python by themselves)
Tips for those who are wondering how to use is and == in Python
For those who want to learn Excel VBA and get started with Python
[Solved] I have a question for those who are familiar with Python mechanize.
Things to keep in mind when using Python for those who use MATLAB
5 Reasons Processing is Useful for Those Who Want to Get Started with Python
Dart grammar for those who only know Python
For those who have done pip uninstall setuptools
Introduction to Programming (Python) TA Tendency for beginners
The first step of machine learning ~ For those who want to implement with python ~
Environment construction for those who want to study python easily with VS Code (for Mac)
For those who should have installed janome properly with Python but get an error
Preparing to start "Python machine learning programming" (for macOS)
For those who get Getting Key Error:'length_seconds' on pytube
How to enjoy Python on Android !! Programming on the go !!
Pepper Web API cooperation explanation For those who have no experience in Pepper application development / programming
An introduction to Web API development for those who have completed the Progate Go course