现充|junyu33

Quick guide from C to python

This tutorial only introduces the basic knowledge points required to use Python as a scripting language. Its purpose is not for machine learning or data analysis, but to help you write short, maintainable, and never-overflowing scripts.

Readers with a solid foundation in C can master these concepts in an afternoon.

This tutorial partially references Liao Xuefeng's blog and is based on Python 3.

Main Differences from C

I/O

with open('D:/tmp1/file.txt','a') as f:
   f.write('this is a trivial test for file I/O.')
with open('D:/tmp1/file.txt') as f:
   content = f.read()
print(content) # However, when the file contains Chinese characters, garbled text appears. "你好" becomes "浣犲ソ". The solution is provided later.
f.close()

Data Type & Conversion

Once a variable is created (assigned), its type is fixed. You can check its type using type(var).

'''hello,
world!''' # Strings can be written across multiple lines.

Encoding

(Finally, I can handle files with Chinese characters!)

Character ASCII Unicode UTF-8
A 01000001 00000000 01000001 01000001
× 01001110 00101101 11100100 10111000 10101101
>>> b'ABC'.decode('ascii')
'ABC'
>>> b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8')
'中文'

Returning to the earlier file I/O example, we only need to add encoding = 'utf-8' when opening the file the second time.

Basic Data Structures

In Python, data structures are treated as objects and come with built-in methods, which is a key difference from procedural C.

list——[]

tuple——()

Once a tuple is created, it cannot be modified.

dict——{}

(Dict is similar to map in C++. I originally thought dict was also implemented using an rb-tree, but an error told me that it is implemented using hashing. Therefore, the elements in a dict must be immutable objects such as strings or tuples, and you cannot insert a list.)

set——set(list)

As the name implies, a set does not contain duplicate elements.

>>> s1 = set([1, 2, 3])
>>> s2 = set([2, 3, 4])
>>> s1 & s2
{2, 3}
>>> s1 | s2
{1, 2, 3, 4}

Condition and Loop

For other considerations in conditional statements, see the example below:

age = int(input())
if age >= 6:
    print('teenager')
elif age >= 18:
    print('adult')
else:
    print('kid')
subjects = ['calculus', 'programming', 'politics']
for i in subjects:
    print(i)
sum = 0
for x in range(101):
    sum = sum + x
print(sum)
sum = 0
for x in range(101):
    if x > 50:
        break
    elif x & 1:
        continue
    sum = sum + x
print(sum)
>>> L = list(range(100))
>>> L[:10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> L[-10:]
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
>>> L[10:20]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> L[:10:2]
[0, 2, 4, 6, 8]
>>> L[::5]
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
>>> L[:]
[0, 1, 2, 3, ..., 99]
>>> L[::-1]
[99, 98, 97, 96, ..., 0]

Function

A simple factorial function:

def fact(n):
    if n==1:
        return 1
    return n * fact(n - 1)
def rot90(x, y):
    tmp = x
    x = -y
    y = tmp
    return x, y

Positional Arguments

They have the same meaning as parameters in the C language.

Default Parameters

For example, the help documentation for the open function is written as follows:

>>> help(open)
Help on built-in function open in module io:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
    Open file and return a stream.  Raise OSError upon failure.

    file is either a text or byte string giving the name (and the path
    if the file isn't in the current working directory) of the file to
    be opened or an integer file descriptor of the file to be
    wrapped. (If a file descriptor is given, it is closed when the
-- More  --

Note: Default parameters must point to immutable objects! Otherwise, the results obtained after each function run may differ.

Summary

The best way to learn a language is to use it.

Go solve problems now!