Python basics
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 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'
tuple fixed array
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'
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 ['A', 'B', 'C']: for y in ['1', '2', '3']: 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 = { '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
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)
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 = ['Adam', 'Lisa', 'Bart', 'Paul'] 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('hello'))
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 = ['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)
迭代dict的value
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()方法不再支持。
迭代dict的key和value
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中文网!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

VS Code not only can run Python, but also provides powerful functions, including: automatically identifying Python files after installing Python extensions, providing functions such as code completion, syntax highlighting, and debugging. Relying on the installed Python environment, extensions act as bridge connection editing and Python environment. The debugging functions include setting breakpoints, step-by-step debugging, viewing variable values, and improving debugging efficiency. The integrated terminal supports running complex commands such as unit testing and package management. Supports extended configuration and enhances features such as code formatting, analysis and version control.
