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 <h2 id="break">break</h2><pre class="brush:php;toolbar:false">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 <h2 id="Multiple-loops">Multiple loops</h2><pre class="brush:php;toolbar:false">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 <h2 id="Variable-parameters">Variable parameters</h2> <pre class="brush:php;toolbar:false">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>%s</td> </tr>' % (name, score) tds = [generate_tr(name,score) for name, score in d.items()] print('
Name | Score |
---|---|
条件表达式
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中文网!

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.


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

SublimeText3 English version
Recommended: Win version, supports code prompts!

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

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