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.
・ 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.
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.
① 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
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.
Comment Starting with \ #, the code after the line is not processed by Python. If you want to comment on multiple lines, enclose it in "" ".
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.
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".
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.
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.
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)
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
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 ().
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.
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.
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