Last Updated on 2021-07-05 by Clay
Introduction
Python is a simple and beautiful program language. Today I will record how to learn Python quickly. The cost time, I think it’s just only one hour.
I will divide it into several subsections below, then let’s get start.
Why should we learn Python?
python is the famous program language, and it has many packages, modules to help us complete our tasks.
And Python is the mainstream of today’s machine learning frameworks. Learning Python’s return on investment (ROI) is very high.
Download & Install
First, we need to download Python Interpreter, I recommend using Python 3.6.
There is not much difference between Python versions, but Python 3.6 runs smoothly in machine learning frameworks.
Go to the Python official website to download it according to your operating system: https://www.python.org/downloads/release/python-368/
If you don’t want to use native Python IDLE to program coding, consider installing Jupyter Notebook or PyCharm.
Print “Hello World”
print('Hello World!')
Output:
Hello World!
print()
is a function to print string in Python.
Operations
print(2+2)
print(50-6)
print(7*7)
print(8/2)
Output:
4
44
49
4.0
Operations are very intuitive.
The data type of 4.0
is “float” and the rest are “int”.
Variable
“Variables” can store values and texts, it’s convenient for us to process.
text = 'Hello'
number = 7
print(text)
print(number)
Output:
Hello
7
For-loop
The for-loop is a program block that can execute our instructions repeatedly. The examples are as follows:
for n in range(10):
print(n)
Output:
0
1
2
3
4
5
6
7
8
9
for n in range(10)
The value of n is executed from 0 to 9. The part below “indentation” is our for-loop to be executed.
While-loop
while-loop is like a for-loop with no set range. Of course, you can set it.
After the while is the “execution condition”, if set “True”, it will always be executed.
n = 0
while True:
n += 1
print(n)
if n == 10:
break
Output:
1
2
3
4
5
6
7
8
9
10
When n is equal to 10, the while loop is ended, and the “if-else” method and flow control will be described later.
If-else
for n in range(1, 10):
if n % 3 == 0:
print(n, 'Divided by 3')
elif n % 3 == 1:
print(n, 'After being divided by 3, the remaining 1')
else:
print(n, 'After being divided by 3, the remaining 2')
Output:
1 After being divided by 3, the remaining 1
2 After being divided by 3, the remaining 2
3 Divided by 3
4 After being divided by 3, the remaining 1
5 After being divided by 3, the remaining 2
6 Divided by 3
7 After being divided by 3, the remaining 1
8 After being divided by 3, the remaining 2
9 Divided by 3
If your program match“the conditions after if
”, the underlying indented code is automatically executed.
elif
is the next judgment condition. if your program not match “if”, it will start to judge the next condition. The program will be executed one “elif” if it match condition.
else
is the part that executes when all the above conditions are not match.
Flow control
There are three types of instructions for flow control: break
, pass
, and continue
.
break
is the instruction to jump out of the loop, no longer here to demo.
pass
is an instruction that does not execute the program, if there are other programs below the judgment in the loop, that can continue to be executed.
for n in range(10):
if n == 4:
pass
else:
print(n)
Output:
1
2
3
5
6
7
8
9
continue
will skip an iteration of the loop.
# Continue
times = 0
for n in range(10):
if n == 4:
continue
else:
print(n)
times += 1
print('we run %d times' % times)
Output:
0
we run 1 times
1
we run 2 times
2
we run 3 times
3
we run 4 times
5
we run 5 times
6
we run 6 times
7
we run 7 times
8
we run 8 times
9
we run 9 times
It can be seen that the program for the 5th time (that is when 4 is printed) is directly interrupted, and is not counted as an execution program.
Bool
“Boolean value” in Python can be represented as “True” or “False”, or as “1” or “0”.
Logic symbol
Function
We can use def
to define a function to modularize our program. We can reuse the defined function.
def fibo(n):
if n == 0: return 0;
elif n == 1: return 1;
return fibo(n-1) + fibo(n-2)
The above is a classic Fibonacci function that we can use like this:
ans = fibo(5)
print(ans)
Output:
5
The value of “n” in the value we can enter into the function. Different input will produce different output.
List
“List” can set the value of different data types in the List, and can be using the for-loop to show.
List = [1, 2, 3, 'Today', 'is', 'nice.']
for value in List:
print(value)
Output:
1
2
3
Today
is
nice.
You can use append()
to add elements.
And can use remove()
to remove elements.
List.append('New')
print('Append:', List)
List.remove('New')
print('Remove:', List)
Output:
Append: [1, 2, 3, 'Today', 'is', 'nice.', 'New']
Remove: [1, 2, 3, 'Today', 'is', 'nice.']
Tuple
The usage f tuple is very similar to List.
But after data storing in the tuple, there is no way to change it.
a = (1, 2, 2, 3, 3, 3, 'a', 'b', 'c', 'c')
print(a.count(2))
print(a.count(3))
print(a.index(1))
print(a.index('a'))
Output:
2
3
0
6
a.count(n)
can calculate how many elements “n” are in the tuple.
a.index(n)
can calculate the position of element “n”.
Set
The data type “set” cannot store the same value, but it can calculate the “intersection”, “union”, and “difference”.
a = set([1, 2, 3, 'a', 'b', 'c'])
b = set([1, 3, 5, 'a', 'c', 'e'])
print('Intersection:', a.intersection(b))
print('Union:', a.union(b))
print('Difference:', a.difference(b))
Output:
Intersection: {'c', 1, 'a', 3}
Union: {'b', 1, 2, 3, 'a', 'e', 5, 'c'}
Difference: {'b', 2}
Dictionary
“Dictionary” is the data type corresponding to “key-value”, which can be used to quickly build a table.
b = dict()
b[1] = 2
b[2] = 4
b[3] = 6
print(b[1])
print(b[2])
print(b[3])
Output:
2
4
6
Import
To use a package written by someone else. or even a Python native package, you must use import
to import the module.
import time
time.sleep(3)
from time import sleep
sleep(3)
time.sleep(n)
is the function that stops the system for “n” seconds. In addition, if you just want to call the function sleep
, you can also use the method from … import …
to import.
Try & Except
In Python, we can use try
and except
for simple error handling.
try:
hello()
except:
print('Error!')
Output:
Error!
We have not defined the hello()
function, so an error occurs when executed under try
. Then, if an error occurs under try
, the program will automatically start executing the program under except
.
This will ensure that even if the program has any problem, it will not cause the program crash.
We can set the program take a different processing mode to avoid the problem by performing error processing in advance.
File reading and writing
in Python, we can use open()
instruction to open the file. in the function open()
, there are three mode: “r”, “w”, and “a”.
Suppose I have a text like this with the following content:
Today is a nice day!
And I saved it, the file name is “test.txt”.
text = open('test.txt', 'r', encoding='utf-8').read()
print(text)
Output:
Today is a nice day!
The first input is the “file name”.
The second input is the “mode”.
The last input is the “encoding”.
Mode “r” is reading the file.
newText = 'Today is not a nice day!'
open('test.txt', 'w', encoding='utf-8').write(newText)
text = open('test.txt', 'r', encoding='utf-8').read()
print(text)
Output:
Today is not a nice day!
Mode “w” is “write”, it will replace all the content in the current text. If the file we specified does not exist, it will be created.
newText = '\nToday is a nice day!'
open('test.txt', 'a', encoding='utf-8').write(newText)
text = open('test.txt', 'r', encoding='utf-8').read()
print(text)
Output:
Today is not a nice day!
Today is a nice day!
Mode “a” is continuation and will continue to write text under the file without overwriting the original content.
‘\n’ is a newline symbol.
Class
class
is an object-oriented instruction in Python.
class Human():
def __init__(self, name, age):
self.name = name
self.age = age
if __name__ == '__main__':
clay = Human('Clay', 25)
print('Name:', clay.name)
print('Age:', clay.age)
Output:
Name: Clay
Age: 25
The class we created is followed by the class
instruction, here we create the “Human” class.
__init__
is the initialized block. When this class is created as an object, the __init__
part is automatically executed.
when we create the “Human” class, we must enter the “name” and the “age”.
In class we can create this class-specific method, which can be created using def
. The method is only available to this class.
Ending
Above, one hour of Python tutorial is over! I roughly estimated that time should be similar, but the writer’s feeling is no reference.
I hope everyone can have fun in coding.