Home  >  Article  >  Backend Development  >  Python basics

Python basics

高洛峰
高洛峰Original
2017-02-16 11:22:281609browse

Preface

Python is a programming language written by Uncle Turtle in 1989 to kill the boring Christmas. It is characterized by elegance, clarity and simplicity. It now has a rich standard library and third-party libraries .
Python is suitable for developing Web websites and various network services, system tools and scripts. It can be used as a "glue" language to package modules developed in other languages, for scientific computing and so on.

The editor has three reasons for learning Python:
In order to crawl all kinds of data needed, you might as well learn Python.
In order to analyze data and mine data, you might as well learn Python.
In order to do some fun and interesting things, you might as well learn Python.

Preparation

1. Download and install your favorite version from the Python official website. The editor is using the latest version 3.6.0.

2. Open IDLE, which is Python's integrated development environment. Although simple, it is extremely useful. IDLE includes an editor with color highlighting for syntax, a debugging tool, Python shell, and a complete set of online documentation for Python 3.

hello world

1. In IDLE, enter print('hello world') and press Enter to print out hello world.
PS: You can add or not add a semicolon at the end of the statement ;. The editor decided not to add a semicolon, which is simpler.

2. Use sublime to create a new file hello.py with the following content:

print('hello world')

Under Windows, shift+right click, open the command window here, and execute python hello.py, press Enter to print out hello world.

3. Use sublime to create a new file hello.py with the following content:

#!/usr/bin/env python
print('hello world')

In a Linux or Mac environment, you can run the script directly. First add execution permission chmod a+x hello.py, and then execute ./hello.py. Of course, you can also use python hello.py to execute the script just like Windows.

Introduce the module

1. Create a new name.py with the following content:

name='voidking'

2. Execute python name.py.
3. Enter python shell mode, execute import name, print(name.name), and voidking will be printed.

Basic syntax

Commonly used functions (print), data types, expressions, variables, conditions and loops, and functions. Similar to other languages, select a part below to expand.

list linked list array

1. Definition array
myList = ['Hello', 100, True]
2. Output array
print(myList)
3. Output array elements
print(myList[0]), print(myList[-1])
4. Append elements to the end
myList.append('voidking')
5. Append elements to the head
myList.insert(0,'voidking')
6. Delete elements
myList.pop(), myList.pop(0)
7. Assign elements
myList[0]='hello666'

tuple fixed array

1. Define the array
myTuple = ('Hello', 100, True)
Incorrect definition: myTuple1=(1), correct definition: myTuple=(1,)
2, output array
print(myTuple)
3. Output array elements
print(myTuple[0])
4. Combining tuple and list
t = ('a', ' b', ['A', 'B'])t[2][0]='X'

if statement

if

score = 75
if score>=60:
    print 'passed'

Enter twice to execute the code.

if-else

if score>=60:
    print('passed')
else:
    print('failed')

if-elif-else

if score>=90:
    print('excellent')
elif score>=80:
    print('good')
elif score>=60:
    print('passed')
else:
    print('failed')

loop

for loop

L = [75, 92, 59, 68]
sum = 0.0
for score in L:
       sum += score
print(sum / 4)

while loop

sum = 0
x = 1
while x<100:
    sum += x
    x = x + 1
print(sum)

break

sum = 0
x = 1
while True:
    sum = sum + x
    x = x + 1
    if x > 100:
        break
print(sum)

continue

L = [75, 98, 59, 81, 66, 43, 69, 85]
sum = 0.0
n = 0
for x in L:
    if x < 60:
        continue
    sum = sum + x
    n = n + 1
print(sum/n)

Multiple loops

for x in [&#39;A&#39;, &#39;B&#39;, &#39;C&#39;]:
    for y in [&#39;1&#39;, &#39;2&#39;, &#39;3&#39;]:
        print(x + y)

dict

The function of dict is to establish a mapping relationship between a set of keys and a set of values. .

d = {
    &#39;Adam&#39;: 95,
    &#39;Lisa&#39;: 85,
    &#39;Bart&#39;: 59,
    &#39;Paul&#39;: 75
}
print(d)
print(d[&#39;Adam&#39;])
print(d.get(&#39;Lisa&#39;))
d[&#39;voidking&#39;]=100
print(d)
for key in d:
    print(key+&#39;:&#39;,d.get(key))

set

set holds a series of elements, which is very similar to list, but the elements of set are not repeated and are unordered, which is very similar to the key of dict.

s = set([&#39;Adam&#39;, &#39;Lisa&#39;, &#39;Bart&#39;, &#39;Paul&#39;])
print(s)
s = set([&#39;Adam&#39;, &#39;Lisa&#39;, &#39;Bart&#39;, &#39;Paul&#39;, &#39;Paul&#39;])
print(s)
len(s)
print(&#39;Adam&#39; in s)
print(&#39;adam&#39; in s)
for name in s:
    print(name)
s = set([(&#39;Adam&#39;, 95), (&#39;Lisa&#39;, 85), (&#39;Bart&#39;, 59)])
for x in s:
    print(x[0]+&#39;:&#39;,x[1])
s.add(100)
print(s)
s.remove((&#39;Adam&#39;,95))
print(s)

Function

Built-in function

del sum
L = [x*x for x in range(1,101)]
print sum(L)

Custom function

def my_abs(x):
    if x >= 0:
        return x
    else:
        return -x
my_abs(-100)

Introducing function library

import math

def quadratic_equation(a, b, c):
    x = b * b - 4 * a * c
    if x < 0:
        return none
    elif x == 0:
        return -b / (2 *a)
    else:
        return ((math.sqrt(x) - b ) / (2 * a)) , ((-math.sqrt(x) - b ) / (2 * a))
print(quadratic_equation(2, 3, 0))
print(quadratic_equation(1, -6, 5))

Variable parameters

def average(*args):
    if args:
        return sum(args)*1.0/len(args)
    else:
        return 0.0

print(average())
print(average(1, 2))
print(average(1, 2, 2, 3, 4))

Slice

list slice

L = [&#39;Adam&#39;, &#39;Lisa&#39;, &#39;Bart&#39;, &#39;Paul&#39;]
L[0:3]
L[:3]
L[1:3]
L[:]
L[::2]

Reverse order slice

L[-2:]
L[-3:-1]
L[-4:-1:2]
L = range(1, 101)
L[-10:]
L[4::5][-10:]

PS: range is an ordered list, which is expressed in the form of a function by default. Execute the range function, that is, you can Expressed in list form.

String slicing

def firstCharUpper(s):
    return s[0:1].upper() + s[1:]

print(firstCharUpper(&#39;hello&#39;))

Iteration

Python’s for loop can be used not only on lists or tuples, but also on any other iterable object.
The iteration operation is for a set, whether the set is ordered or unordered, we can always take out each element of the set in sequence using a for loop.
A collection refers to a data structure containing a set of elements, including:

  • Ordered collection: list, tuple, str and unicode;

  • Unordered set: set

  • Unordered set with key-value pairs: dict

for i in range(1,101):
    if i%7 == 0:
        print(i)

Index iteration

For ordered sets, elements are indexed. What if we want to get the index in a for loop? The method is to use the enumerate() function.

L = [&#39;Adam&#39;, &#39;Lisa&#39;, &#39;Bart&#39;, &#39;Paul&#39;]
for index, name in enumerate(L):
    print(index+1, &#39;-&#39;, name)

myList = zip([100,20,30,40],L);
for index, name in myList:
    print(index, &#39;-&#39;, name)

迭代dict的value

d = { &#39;Adam&#39;: 95, &#39;Lisa&#39;: 85, &#39;Bart&#39;: 59 }
print(d.values())
for v in d.values():
    print(v)

PS:Python3.x中,dict的方法dict.keys(),dict.items(),dict.values()不会再返回列表,而是返回一个易读的“views”。这样一来,k = d.keys();k.sort()不再有用,可以使用k = sorted(d)来代替。
同时,dict.iterkeys(),dict.iteritems(),dict.itervalues()方法不再支持。

迭代dict的key和value

d = { &#39;Adam&#39;: 95, &#39;Lisa&#39;: 85, &#39;Bart&#39;: 59 }
for key, value in d.items():
    print(key, &#39;:&#39;, value)

列表生成

一般表达式

L = [x*(x+1) for x in range(1,100)]
print(L)

复杂表达式

d = { &#39;Adam&#39;: 95, &#39;Lisa&#39;: 85, &#39;Bart&#39;: 59 }
def generate_tr(name, score):
    if score >=60:
        return '<tr><td>%s</td><td>%s</td></tr>' % (name, score)
    else:
        return '<tr><td>%s</td><td style="color:red">%s</td></tr>' % (name, score)

tds = [generate_tr(name,score) for name, score in d.items()]
print('<table border="1">')
print('<tr><th>Name</th><th>Score</th><tr>')
print('\n'.join(tds))
print('</table>')

条件表达式

L = [x * x for x in range(1, 11) if x % 2 == 0]
print(L)
def toUppers(L):
    return [x.upper() for x in L if isinstance(x,str)]

print(toUppers(['Hello', 'world', 101]))

多层表达式

L = [m + n for m in 'ABC' for n in '123']
print(L)
L = [a*100+b*10+c for a in range(1,10) for b in range(0,10) for c in range(1,10) if a==c]
print(L)

后记

至此,Python基础结束。接下来,爬虫飞起!

更多Python,基础相关文章请关注PHP中文网!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn