Home > Article > Backend Development > Python basics
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.
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.
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.
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.
Commonly used functions (print), data types, expressions, variables, conditions and loops, and functions. Similar to other languages, select a part below to expand.
1. Definition arraymyList = ['Hello', 100, True]
2. Output arrayprint(myList)
3. Output array elementsprint(myList[0])
, print(myList[-1])
4. Append elements to the endmyList.append('voidking')
5. Append elements to the headmyList.insert(0,'voidking')
6. Delete elementsmyList.pop()
, myList.pop(0)
7. Assign elements myList[0]='hello666'
1. Define the arraymyTuple = ('Hello', 100, True)
Incorrect definition: myTuple1=(1)
, correct definition: myTuple=(1,)
2, output arrayprint(myTuple)
3. Output array elementsprint(myTuple[0])
4. Combining tuple and listt = ('a', ' b', ['A', 'B'])
,t[2][0]='X'
score = 75 if score>=60: print 'passed'
Enter twice to execute the code.
if score>=60: print('passed') else: print('failed')
if score>=90: print('excellent') elif score>=80: print('good') elif score>=60: print('passed') else: print('failed')
L = [75, 92, 59, 68] sum = 0.0 for score in L: sum += score print(sum / 4)
sum = 0 x = 1 while x<100: sum += x x = x + 1 print(sum)
sum = 0 x = 1 while True: sum = sum + x x = x + 1 if x > 100: break print(sum)
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)
for x in ['A', 'B', 'C']: for y in ['1', '2', '3']: print(x + y)
The function of dict is to establish a mapping relationship between a set of keys and a set of values. .
d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59, 'Paul': 75 } print(d) print(d['Adam']) print(d.get('Lisa')) d['voidking']=100 print(d) for key in d: print(key+':',d.get(key))
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(['Adam', 'Lisa', 'Bart', 'Paul']) print(s) s = set(['Adam', 'Lisa', 'Bart', 'Paul', 'Paul']) print(s) len(s) print('Adam' in s) print('adam' in s) for name in s: print(name)
s = set([('Adam', 95), ('Lisa', 85), ('Bart', 59)]) for x in s: print(x[0]+':',x[1])
s.add(100) print(s) s.remove(('Adam',95)) print(s)
del sum L = [x*x for x in range(1,101)] print sum(L)
def my_abs(x): if x >= 0: return x else: return -x my_abs(-100)
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))
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))
L = ['Adam', 'Lisa', 'Bart', 'Paul'] L[0:3] L[:3] L[1:3] L[:] L[::2]
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.
def firstCharUpper(s): return s[0:1].upper() + s[1:] print(firstCharUpper('hello'))
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)
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 = ['Adam', 'Lisa', 'Bart', 'Paul'] for index, name in enumerate(L): print(index+1, '-', name) myList = zip([100,20,30,40],L); for index, name in myList: print(index, '-', name)
d = { 'Adam': 95, 'Lisa': 85, 'Bart': 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()方法不再支持。
d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59 } for key, value in d.items(): print(key, ':', value)
L = [x*(x+1) for x in range(1,100)] print(L)
d = { 'Adam': 95, 'Lisa': 85, 'Bart': 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中文网!