Getting Started with Python Basics of Python

index -Introduction to Python Python Basics -Introduction to Python Scientific Calculations with Python -Introduction to Python Machine Learning Basics (Unsupervised Learning / Principal Component Analysis)

How to use Jupyter Notebook

Read the following to install and learn how to use it. Indispensable for data analysis! How to use Jupyter Notebook [For beginners]

Python basics

variable

When creating a string, enclose it in single or double quotes. Also ** Python basically doesn't require variable type declarations. ** You can use it just by assigning a value.


msg = 'test'
print(msg) #output:test

Calculation


data = 1
print(data) #output: 1

data = data + 10
print(data) #output: 11

list

** List ** is for handling multiple values as a group. Same as ** arrays in other languages. ** **


data_list = [1,2,3,4,5,6,7,8,9,10]
print(data_list) #output: [1,2,3,4,5,6,7,8,9,10]
print('Second number:', data_list[1]) #output:Second number:2
print('Element count:', len(data_list)) #output: Element count:10

#Multiplying the list by 2 just repeats the entire list again. If you want to double, use for statement or Numpy
print(data_list * 2) #output: [1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10]

Use ʻappend to add list elements, remove, pop, del`, etc. to remove them.

data_list2 = [1,2,3,4,5]
print(data_list2) #output: [1,2,3,4,5]

#Finds the same element as the value specified in parentheses and removes the first element
data_list2.remove(1) 
print(data_list2) #output: [2,3,4,5]
data_list3 = [1,2,3]
data_list3.append(10)
print(data_list3) #output: [1, 2, 3, 10]

Dictionary type

In the dictionary type, ** keys and values can be paired to manage multiple elements **. To represent a dictionary in Python, use a stove delimiter such as {key: value}. It is used when you want to keep the value for some specified key such as "apple is 100" and "banana is 200" as in the following example.

dic_data = {'apple':100, 'banana':200}
print(dic_data['banana']) #output: 200
dic_data["banana"] #output: 200

If you want to add a dictionary element, target dictionary [key] = element

dic_data ["orange"] = 300
print(dic_data) #output: {'apple': 100, 'banana': 200, 'orange': 300}

If you want to delete a dictionary element, del target dictionary [key]

del dic_data["apple"]
print(dic_data) #output: {'banana': 200, 'orange': 300}

[Addition] If you want to retrieve only the keys and values as a ** list **, use .keys () or .values (). The acquired list is acquired as dict_keys and dict_values, respectively.

dic_data = {'apple':100, 'banana':200}
dic_data.keys() #output: dict_keys(['apple', 'banana'])
dic_data.values() #output: dict_values([100, 200])

The following for statement is also extracted using keys () and values (), but if you use the for statement, you can extract all the keys and values in order instead of the list.

Tuple

It is a type that can store multiple values like a list, but the difference is that ** cannot be changed ** and ** execution speed is a little faster **. Explanation of how to use tuples and differences from lists

list_sample = [1, 2, 3, 4, 5]
tuple_sample = (1, 2, 3, 4, 5)
#You don't have to have parentheses
tuple_sample2 = 1, 2, 3, 4, 5

print(list_sample) #output: [1, 2, 3, 4, 5]
print(tuple_sample) #output: (1, 2, 3, 4, 5)
print(tuple_sample2) #output: (1, 2, 3, 4, 5)

set

A set is also a type that can store multiple values like a list, but ** duplicate elements are ignored ** points and ** elements are out of order ** points are different. [Introduction to Python] Easy to understand! Basic summary of set type (set type)

set_data1 = set([1,2,3])
set_data2 = set([1,2,3,3,2,1])
print(set_data1) #output: {1, 2, 3}
print(set_data2) #output: {1, 2, 3}

if statement

if [Conditional expression]:
    [Processing to be performed when the conditional expression is True]
else:
    [Processing to be performed when the conditional expression is False]

ʻEl if is ʻelse if in other languages

if [Conditional expression 1]:
    [Processing to be performed when the conditional expression is True]
elif [Conditional expression 2]:
    [Processing to be performed when conditional expression 2 of elif is True]
else:
    [Processing to be performed when both conditional expression 1 of if statement and conditional expression 2 of elif are False]

data_list4 = [1,2,3,4,5,6]
findvalue = 10

if findvalue in data_list4:
    print('{0}Was found.' .format(findvalue))
else:
    print('{0}Was not found.' .format(findvalue))

#output:10 was not found.

The 'string'.format (value, ...) used to display the result is called the string format, and the {0} specified above is the value specified at the beginning of the format brackets. It is a specification to embed.


print('{0}When{1}を足すWhen{2}is.' .format(2,3,5))
#output:Add 2 and 3 to get 5.

for statement

It behaves like any other language. Refer to the following for how to write.


data_list5 = [1,2,3,4,5]
total = 0

for num in data_list5:
    total += num
    
print('total:',total) #output: total: 15

When retrieving an element using a for statement in a dictionary type key () method: retrieve key values () method: Fetch values. `` ʻItems () method: Extract both. There are three of .


dic_data2 = {'apple':100, 'banana':200, 'orange':300}

for all_data in dic_data2:
    print(all_data) 

#output: apple
#      banana
#      orange

for all_data in dic_data2.keys():
    print(all_data)

#output: apple
#      banana
#      orange

for all_data in dic_data2.values():
    print(all_data)

#output: 100
#      200
#      300

for all_data in dic_data2.items():
    print(all_data)

#output: ('apple', 100)
#      ('banana', 200)
#      ('orange', 300)

for all_data1,all_data2 in dic_data2.items():
    print(all_data1,all_data2)

#output: apple 100
#      banana 200
#      orange 300

range function

A function to use when you want to create a continuous list of integers. Note that when range (N) is set, an integer from 0 to N-1 is output.


for i in range(10):
    print(i)

output


0
1
2
3
4
5
6
7
8
9

In addition, the range function allows you to specify first value, last value-1, and skip value in parentheses.

#Skip 2 pieces from 1 to 9
for i in range(1,10,2):
    print(i)

output


1
3
5
7
9

Comprehension notation

How to create a result as another list of the data retrieved using the for statement.

#Extract the value from data and store it in the variable i. Double this to data1
data = [1,2,3,4,5]
data1 = []

data1 = [i * 2 for i in data]
print(data1) #output: [2, 4, 6, 8, 10]

You can also specify conditions and include only those that meet the conditions in the new list. It can be seen that only ʻi` that meets the conditions is taken out first and doubled.

data = [1,2,3,4,5]
[i * 2 for i in data if i % 2 ==0] #output: [4, 8]

zip function

Executes the process of fetching different lists at the same time. For example, if you have two lists, [1,2,3] and [11,12,13], they will be displayed with the same index.

for x , y in zip([1,2,3], [11,12,13]):
    print(x, 'When', y)

output


1 and 11
2 and 12
3 and 13

while statement

num = 1 #initial value
while num <= 10:
    print(num)
    num = num + 1

output


1
2
3
4
5
6
7
8
9
10

function

A mechanism to put together a series of processes. As a way of writing, if there is a function name and an argument after def, describe the argument name in (). This argument becomes an input, the result is returned by return (return value), and this is the output.

def calc_multi(a,b):
    return a*b

calc_multi(3,10) #output: 30

Anonymous function

Some functions are called anonymous functions, which can be used to simplify your code. To write an anonymous function, use the keyword lambda. Anonymous functions are often used when you want to perform some function on an element such as a list.

(lambda a,b: a*b)(3,10) #output: 30

Here, lambda a, b: is the part corresponding to the function name (a, b). The basic way to write an anonymous function is to describe the processing of the function (here, return a * b) by separating it with: . map If you want to do something with the element, use the map function. A function that uses a function as an argument or return value, and is used when you want to process or operate on each element.

def calc_double(x):
    return x * 2

#When using for
for num in [1,2,3,4]:
    print(calc_double(num)) #output: ①
    
#When using the map function
list(map(calc_double, [1,2,3,4])) #output: ②

output


Output of ①
2
4
6
8

Output of ②[2, 4, 6, 8]

If you use an anonymous function, you can directly describe the processing of the function without preparing a separate function.

list(map(lambda x : x * 2, [1,2,3,4])) #output: [2, 4, 6, 8]

Recommended Posts

Getting Started with Python Basics of Python
1.1 Getting Started with Python
Getting Started with Python
Getting Started with Python for PHPer-Super Basics
Getting Started with Python Django (1)
Getting Started with Python Django (4)
Getting Started with Python Django (3)
Getting Started with Python Django (6)
Python3 | Getting Started with numpy
Getting Started with Python Django (5)
Getting Started with Python responder v2
Getting Started with Python Web Applications
Getting Started with Python for PHPer-Classes
Basics of Python ①
Basics of python ①
Getting Started with Python Genetic Algorithms
Getting started with Python 3.8 on Windows
Getting Started with Python for PHPer-Functions
Basics of binarized image processing with Python
Getting Started with python3 # 1 Learn Basic Knowledge
Getting Started with Python Web Scraping Practice
Getting started with Dynamo from Python boto
Django 1.11 started with Python3.6
Getting started with Android!
Basics of Python scraping basics
Getting started with apache2
Getting Started with Golang 1
Getting Started with Django 1
Getting Started with Optimization
Getting Started with Golang 3
# 4 [python] Basics of functions
Getting Started with Numpy
Getting started with Spark
Getting Started with Pydantic
Getting Started with Golang 4
Basics of python: Output
Getting Started with Jython
Getting Started with Django 2
Getting started with Python with 100 knocks on language processing
[Translation] Getting Started with Rust for Python Programmers
Getting started with AWS IoT easily in Python
Materials to read when getting started with Python
Settings for getting started with MongoDB in python
Translate Getting Started With TensorFlow
Getting Started with Tkinter 2: Buttons
Getting Started with Go Assembly
Getting Started with PKI with Golang ―― 4
python: Basics of using scikit-learn ①
Get started with Python! ~ ② Grammar ~
Getting Started with Django with PyCharm
Basics of Python × GIS (Part 1)
Getting Started with python3 # 2 Learn about types and variables
Getting Started with Google App Engine for Python & PHP
[Basics of Modern Mathematical Statistics with python] Chapter 1: Probability
[Basics of data science] Collecting data from RSS with python
Basics of Python x GIS (Part 3)
Python basics ⑤
Paiza Python Primer 5: Basics of Dictionaries
Get started with Python! ~ ① Environment construction ~
SNS Python basics made with Flask
Link to get started with python