Easy Python to learn while writing

The readers of this article are intended to be new to Python. After reading, my goal is to be able to read and write basic Python code.

Why python?

・ Low learning cost A simple and easy-to-remember programming language. ·Open Source It can be used free of charge. ・ Abundant library of machine learning and data science In the field of deep learning, frameworks such as Caffe, TensorFlow, and Chainer can be used.

Which do you use, Python 2 series or 3 series?

Currently, there are two types of Python, 3 series (Python3) and 2 series (Python2). Conclusion. If you are starting from now on, 3 system is good.   ·function The latest version is the 3rd series, which has improved functions compared to the 2nd series. ·compatibility The 3rd and 2nd code are not compatible. ·support Support for Series 2 will end in 2020.

Run

① Create a file called "sample.py". (2) Open the file with Notepad, write print ("Hello World"), and save it. ③ Open a command prompt and execute the python command.

Move to the "sample.py" folder created by the $ cd # cd command $ python sample.py # Specify the file name "sample.py" in the argument of the python command and execute it. Hello World # Hello World is displayed.

-Enclose characters in single or double quotation marks. -When handling Japanese, write "\ # coding: utf-8" at the beginning of the file.

◆ Exercises

  1. Change "Hello World" to Japanese "Hello World" and display it.

Basic grammar

  1. Variable Variables can be defined using the alphabet. Variables can also change their values.

    cats = 5 print(cats) 5

    cats = 10 print(cats) 10

-Python does not explicitly specify the type and is automatically determined according to the situation. -Python has no constants.

◆ Exercises 2) Change the value of the variable cats to 13 and display it.

  1. Comment Starting with \ #, the code after the line is not processed by Python. If you want to comment on multiple lines, enclose it in "" ".

  2. Arithmetic calculation Can be added or multiplied.

5 + 2 # Addition 7

13-8 # Subtraction 5

7 * 4 # Multiplication 28

7/5 # Division 1.4

4 ** 2 # Power 16

13% 3 # remainder 1

◆ Exercises 3) Display the calculation result of 66-19. 4) Display the calculation result of 9 ** 3.

  1. if statement Conditional branch.

    cats = 12

if cats == 2: # Don't forget the colon print (“2 cats”) #Processing when cats is 2 elif cats> 10: # Don't forget the colon print (“more than 10 cats”) # What to do if cats are greater than 10 else: # Don't forget the colon print (“Other values”) # Processing when neither condition is met More than 10 cats

Place four whitespace characters as indents. Tab characters can be used instead. Comparison operators include ==,! =,> =, <=, <,>.

◆ Exercises 5) When the value of cats is 5 or more, add a condition to display "5 or more".

  1. for statement Iterative processing.

for x in [5, 10, 12]: # Don't forget the colon print (x) # indent 5 10 12

If it comes out in the middle of the repetition, break. If you want to repeat from 1 to 100, use range (1, 100).

◆ Exercises 6) Sum the values from 1 to 50 and display them.

  1. Function A unity of processing. Insert four whitespace characters as indentation. Tab characters can be used instead.

def thank (): Declare a function with #def. Don't forget the colon print (“thank you !!”) #Indent thank () #call the thank function thank you!!

Functions can also be given values as arguments.

def goodbye (name, message): # Don't forget the colon return “goodbye” + name + message # return to return value x = goodbye(“Tom”, ". see you again!") print(x) goodbye Tom. see you again!

◆ Exercises 7) Create an addition function. Also, use the created function to display the calculation result of 3 + 49. 8) Complete a program that meets the following three conditions. Display "1" for the first player. b. The next player will display the next number of the previous player. c. However, if it is divisible by 3, "Fizz", If it is divisible by 5, "Buzz", If it is divisible by both, display "Fizz Buzz" instead of the number.

A little more about the mold

  1. Data type Represents the nature of the data.

type (29) # integer type <class 'int'>

type (“japan”) # string type <class 'str'>

type (5.291) # floating point type <class 'float'>

It can be converted to integer type with int () and to string type with str ().

>>> print( int(50) + 9 )
59

◆ Exercises 9) Execute the following code to eliminate the error that occurred.

>>> count = 100               
>>> x = "200"    
>>> print(count + x)
  1. Boolean type True and False. Used for conditional branching.

    clever = True
    beautiful = False type(clever) <class 'bool'>

clever and beautiful # and = Both are True False

clever or beautiful # or = Either is True True

  1. List type An array.

    a = [4, 81, 47, 28, 3] print(a) [4, 81, 47, 28, 3]

len (a) # number of arrays 5

a.sort () #sort print(a) [3, 4, 28, 47, 81]

a [0] #first value 3

a [4] = 55 # change value print(a) [3, 4, 28, 47, 55]

The array starts with a [0]. The subscript of [] is called an index.

>>> print(a)
[3, 4, 28, 47, 55]

a [0: 2] # Extract two elements from 0 [3, 4]

a [1:] # Index 1 ~ Extract elements [4, 28, 47, 55]

a [: -1] #Reduce one element [3, 4, 28, 47]

Reverse () to sort in descending order. If you want to add an element, append ().

  1. Dictionary type Words and data can be linked like a dictionary.

cat = {} # Create an empty dictionary type cat = {'age': 8,'weight': 2} #age is age, weight is weight cat[‘age’] 8

cat [‘weight’] = 4 # Substitute a value cat['weight'] 4

◆ Exercises 10) Add the name'mike' to the example variable cat.

  1. Class In addition to the built-in types such as the prepared character types, you can create any type yourself.

    class Car(object):

def __init __ (self, name): # Constructor. Initialization process self.name = name def tellme_name (self): # The first argument is self print("Mycar's name is {0}".format(self.name)) myCar = Car("Prius") myCar.tellme_name() Mycar's name is Prius

◆ Exercises 11) Create a calculator class that allows addition and subtraction.

Use external libraries conveniently

In addition to standard libraries such as len and str, Python has useful libraries.  http://docs.python.jp/3/library/

These external libraries need to be imported as needed.

import random # Import a library of random numbers i = random.randrange (1, 6) # Generate random numbers up to 1-6 print(i) 3

import requests # import HTTP library url = "http://google.co.jp" #Specify google as the connection destination url parameter = "{'code': 81}"
url = requests.get(url, params=parameter) # get! print (r.status_code) #Connection result code. Returns 200 if the acquisition is successful. Get the content in text. 200

◆ Exercises 12) Using the random function Create an Omikuji that randomly displays "Daikichi", "Nakayoshi", "Sueyoshi", and "Daiken".

Recommended Posts

Easy Python to learn while writing
Introduction to Python For, While
Easy way to customize Python import
Easy to use Jupyter notebook (Python3.5)
[Python Tutorial] An Easy Introduction to Python
Regular expressions that are easy and solid to learn in Python
Reintroduction to Python Decorators ~ Learn Decorators by Type ~
Learn the basics while touching python Variables
Easy way to use Wikipedia in Python
Updated to Python 2.7.9
Python is easy
Basic Python writing
"Backport" to python 2
Learn python gestures
[Python] Easy introduction to machine learning with python (SVM)
Python for super beginners Python for super beginners # Easy to get angry
Easy way to use Python 2.7 on Cent OS 6
Python list comprehensions that are easy to forget
[Introduction to Udemy Python3 + Application] 40.while else statement
From easy git installation to docker startup python
An easy way to call Java from Python
Easy way to check the source of Python modules
[Introduction to Python] How to use while statements (repetitive processing)
How to install Python
Changes from Python 3.0 to Python 3.5
Changes from Python 2 to Python 3.0
The first algorithm to learn with Python: FizzBuzz problem
Rewrite Python2 code to Python3 (2to3)
Easy to use Flask
How to install python
python decorator to retry
Introduction to Python language
Introduction to OpenCV (python)-(2)
It's not easy to write Python, it's easy to write numpy and scipy
Note to daemonize python
Introducing Python 2.7 to CentOS 6.6
Easy to use SQLite3
Connect python to mysql
[Python MinMaxScaler] Normalize to 0 ~ 1
Tips to look at before you start writing Python
Easy to use Nifty Cloud API with botocore and python
[Python] Get used to Keras while implementing Reinforcement Learning (DQN)
Python sample to learn XOR with genetic algorithm with neural network
Python regular expression basics and tips to learn from scratch
[Introduction to Udemy Python3 + Application] 39. while statement, continue statement and break statement
How to learn TensorFlow for liberal arts and Python beginners
Tips for coding short and easy to read in Python
Five useful Python data types that are easy to forget
Convenient writing method when appending to list continuously in Python
Python code for writing CSV data to DSX object storage
13th Offline Real-time How to Solve Writing Problems in Python
[Python] Notes on while statements (writing style and infinite loop)
PyArmor ~ Easy way to encrypt and deliver python source code ~
Connect to BigQuery with Python
[2020.8 latest] How to install Python
[python] Convert date to string
Post from Python to Slack
How to install Python [Windows]
Post to vim → Python → Slack
Introduction to Python Django (2) Win
Introduction to Cython Writing [Notes]