Table of Contents
Preface
Preparation
hello world
Introduce the module
Basic syntax
list linked list array
tuple fixed array
if statement
if
if-else
if-elif-else
loop
for loop
while loop
break
continue
Multiple loops
dict
set
Function
Built-in function
Custom function
Introducing function library
Variable parameters
Slice
list slice
Reverse order slice
String slicing
Iteration
Index iteration
迭代dict的value
迭代dict的key和value
列表生成
一般表达式
复杂表达式
条件表达式
多层表达式
后记

Python basics

Feb 16, 2017 am 11:22 AM
python

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')
Copy after login

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')
Copy after login

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'
Copy after login

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'
Copy after login

Enter twice to execute the code.

if-else

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

if-elif-else

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

loop

for loop

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

while loop

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

break

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

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)
Copy after login

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)
Copy after login

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))
Copy after login

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)
Copy after login
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])
Copy after login
s.add(100)
print(s)
s.remove((&#39;Adam&#39;,95))
print(s)
Copy after login

Function

Built-in function

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

Custom function

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

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))
Copy after login

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))
Copy after login

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]
Copy after login

Reverse order slice

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

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;))
Copy after login

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)
Copy after login

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)
Copy after login

迭代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)
Copy after login

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)
Copy after login

列表生成

一般表达式

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

复杂表达式

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>')
Copy after login

条件表达式

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

print(toUppers(['Hello', 'world', 101]))
Copy after login

多层表达式

L = [m + n for m in 'ABC' for n in '123']
print(L)
Copy after login
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)
Copy after login

后记

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

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

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

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.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

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.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

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.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

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.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

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: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

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.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

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.

Can visual studio code run python Can visual studio code run python Apr 15, 2025 pm 08:00 PM

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.

See all articles