Table of Contents
Why use Python
Python application scenarios
2 Quick Start
2.1 Hello world
2.2 International support
2.3 Convenient and easy-to-use calculator
2.4 String, ASCII and UNICODE
2.5 Using List
2.6 Conditional and loop statements
2.7 How to define a function
2.10 Classes and inheritance
2.11 Package mechanism
总结
Home Backend Development Python Tutorial Python introductory tutorial: Learn Python in 1 hour in detail_python

Python introductory tutorial: Learn Python in 1 hour in detail_python

May 30, 2018 pm 02:50 PM
python Getting Started Tutorial learn

This article is suitable for experienced programmers to enter the world of Python as soon as possible. In particular, if you master Java and Javascript, you can quickly and smoothly write useful Python programs in Python in less than an hour.

Why use Python

Suppose we have such a task: simply test whether the computers in the LAN are connected. The IP range of these computers is from 192.168.0.101 to 192.168.0.200.
Idea: Use shell programming. (Linux usually It is bash and Windows is a batch script). For example, on Windows, use the ping ip command to test each machine in sequence and get the console output. Because the console text is usually "Reply from..." when the ping succeeds, it does not work. The text is "time out...", so by searching the string in the result, you can know whether the machine is connected.
Implementation: The Java code is as follows:

String cmd="cmd.exe ping ";
String ipprefix="192.168.10.";
int begin=101;
int end=200;
Process p=null;

for(int i=begin;i<end;i++){
     p= Runtime.getRuntime().exec(cmd+i);
     String line = null;
     BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
     while((line = reader.readLine()) != null)
     {
         //Handling line , may logs it. 
     }
    reader.close();
    p.destroy();
}
Copy after login

This paragraph The code runs fine, the problem is that in order to run this code, you need to do some extra work. This extra work includes:

  • Write a class file

  • Write a main method

  • Compile it into byte code

  • Because byte code cannot To run it directly, you need to write a small bat or bash script to run it.

Of course, this work can also be done with C/C++. But C/C++ is not cross-platform Language. In this simple enough example, you may not be able to see the difference between C/C++ and Java implementation, but in some more complex scenarios, such as recording connectivity information to a network database. Due to the network differences between Linux and Windows The interface implementation is different, and you have to write two versions of the function. There is no such concern in Java.
The same work is implemented in Python as follows:

import subprocess

cmd="cmd.exe"
begin=101
end=200
while begin<end:

    p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,
                   stdin=subprocess.PIPE,
                   stderr=subprocess.PIPE)
    p.stdin.write("ping 192.168.1."+str(begin)+"\n")

    p.stdin.close()
    p.wait()

    print "execution result: %s"%p.stdout.read()
Copy after login

Comparing the implementation of Java and Python It’s more concise, and you write faster. You don’t need to write the main function, and the program can be run directly after saving it. In addition, like Java, Python is also cross-platform.
Experienced C/Java programmers It may be argued that writing in C/Java is faster than writing in Python. This point of view has different opinions. My idea is that when you master both Java and Python, you will find that writing such programs in Python will be much faster than in Java. .For example, when operating local files, you only need one line of code and do not need many stream wrapper classes in Java. Various languages ​​​​have their naturally suitable application ranges. Using Python to process some short programs is the most time-saving work similar to interactive programming with the operating system. Effort-saving.

Python application scenarios

Simple enough tasks, such as some shell programming. If you like to use Python to design large-scale commercial websites or design complex games, you are welcome to do so.

2 Quick Start

2.1 Hello world

After installing Python (my version is 2.5.4), open IDLE (Python GUI), the program is Python language interpreter, the statement you write can be run immediately. We write down a famous program statement:

print "Hello,world!"
Copy after login

and press Enter. You can see this sentence introduced into the programming world by K&R Famous quotes.
Select "File"--"New Window" or shortcut Ctrl+N in the interpreter to open a new editor. Write the following statement:

print "Hello,world!"
raw_input("Press enter key to close this window");
Copy after login

Save It is a.py file. Press F5 and you can see the running results of the program. This is the second running method of Python.
Find the a.py file you saved and double-click. You can also see the program results. .Python programs can be run directly, which is an advantage compared to Java.

2.2 International support

Let’s greet the world in another way. Create a new editor and write the following code:

print "欢迎来到奥运中国!"
raw_input("Press enter key to close this window");
Copy after login

When you save the code, Python will prompt you whether to change the character set of the file. The result is as follows:

# -*- coding: cp936 -*- 

print "欢迎来到奥运中国!"
raw_input("Press enter key to close this window");
Copy after login

Change the character set to one we are more familiar with In the form:

# -*- coding: GBK -*- 

print "欢迎来到奥运中国!" # 使用中文的例子
raw_input("Press enter key to close this window");
Copy after login

The program also runs well.

2.3 Convenient and easy-to-use calculator

Use the calculator provided by Microsoft Counting is too troublesome. Open the Python interpreter and calculate directly:

a=100.0
b=201.1
c=2343
print (a+b+c)/c
Copy after login
2.4 String, ASCII and UNICODE

You can print out the string in the predefined output format as follows:

print """
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
"""
Copy after login

How is the string accessed? Please see this example:

word="abcdefg"
a=word[2]
print "a is: "+a
b=word[1:3]
print "b is: "+b # index 1 and 2 elements of word.
c=word[:2]
print "c is: "+c # index 0 and 1 elements of word.
d=word[0:]
print "d is: "+d # All elements of word.
e=word[:2]+word[2:]
print "e is: "+e # All elements of word.
f=word[-1]
print "f is: "+f # The last elements of word.
g=word[-4:-2]
print "g is: "+g # index 3 and 4 elements of word.
h=word[-2:]
print "h is: "+h # The last two elements.
i=word[:-2]
print "i is: "+i # Everything except the last two characters
l=len(word)
print "Length of word is: "+ str(l)
Copy after login

Please note the difference between ASCII and UNICODE strings:

print "Input your Chinese name:"
s=raw_input("Press enter to be continued");
print "Your name is  : " +s;
l=len(s)
print "Length of your Chinese name in asc codes is:"+str(l);
a=unicode(s,"GBK")
l=len(a)
print "I&#39;m sorry we should use unicode char!Characters number of your Chinese \
name in unicode is:"+str(l);
Copy after login
2.5 Using List

Similar to List in Java, this is a convenient and easy-to-use data type:

word=[&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;,&#39;e&#39;,&#39;f&#39;,&#39;g&#39;]
a=word[2]
print "a is: "+a
b=word[1:3]
print "b is: "
print b # index 1 and 2 elements of word.
c=word[:2]
print "c is: "
print c # index 0 and 1 elements of word.
d=word[0:]
print "d is: "
print d # All elements of word.
e=word[:2]+word[2:]
print "e is: "
print e # All elements of word.
f=word[-1]
print "f is: "
print f # The last elements of word.
g=word[-4:-2]
print "g is: "
print g # index 3 and 4 elements of word.
h=word[-2:]
print "h is: "
print h # The last two elements.
i=word[:-2]
print "i is: "
print i # Everything except the last two characters
l=len(word)
print "Length of word is: "+ str(l)
print "Adds new element"
word.append(&#39;h&#39;)
print word
Copy after login
2.6 Conditional and loop statements
# Multi-way decision
x=int(raw_input("Please enter an integer:"))
if x<0:
    x=0
    print "Negative changed to zero"

elif x==0:
    print "Zero"

else:
    print "More"


# Loops List
a = [&#39;cat&#39;, &#39;window&#39;, &#39;defenestrate&#39;]
for x in a:
    print x, len(x)
Copy after login
2.7 How to define a function
# Define and invoke function.
def sum(a,b):
    return a+b


func = sum
r = func(5,6)
print r

# Defines function with default argument
def add(a,b=2):
    return a+b
r=add(1)
print r
r=add(1,5)
print r
Copy after login

And, introduce a convenient and easy-to-use function:

# The range() function
a =range(5,10)
print a
a = range(-2,-7)
print a
a = range(-7,-2)
print a
a = range(-2,-11,-3) # The 3rd parameter stands for step
print a
Copy after login

2.8 File I/O

spath="D:/download/baa.txt"
f=open(spath,"w") # Opens file for writing.Creates this file doesn&#39;t exist.
f.write("First line 1.\n")
f.writelines("First line 2.")

f.close()

f=open(spath,"r") # Opens file for reading

for line in f:
    print line

f.close()
Copy after login

2.9 Exception handling

s=raw_input("Input your age:")
if s =="":
    raise Exception("Input must no be empty.")

try:
    i=int(s)
except ValueError:
    print "Could not convert data to an integer."
except:
    print "Unknown exception!"
else: # It is useful for code that must be executed if the try clause does not raise an exception
    print "You are %d" % i," years old"
finally: # Clean up action
    print "Goodbye!"
Copy after login
2.10 Classes and inheritance
class Base:
    def __init__(self):
        self.data = []
    def add(self, x):
        self.data.append(x)
    def addtwice(self, x):
        self.add(x)
        self.add(x)

# Child extends Base
class Child(Base):
    def plus(self,a,b):
        return a+b

oChild =Child()
oChild.add("str1")
print oChild.data
print oChild.plus(2,3)
Copy after login
2.11 Package mechanism

Each .py file is called a module, and modules can interact with each other Import. Please see the following example:

# a.py
def add_func(a,b):
    return a+b
Copy after login
# b.py
from a import add_func # Also can be : import a

print "Import add_func from module a"
print "Result of 1 plus 2 is: "
print add_func(1,2)    # If using "import a" , then here should be "a.add_func"
Copy after login

module可以定义在包里面.Python定义包的方式稍微有点古怪,假设我们有一个parent文件夹,该文件夹有一个child子文件夹.child中有一个module a.py . 如何让Python知道这个文件层次结构?很简单,每个目录都放一个名为_init_.py 的文件.该文件内容可以为空.这个层次结构如下所示:

parent 
  --__init_.py
  --child
    -- __init_.py
    --a.py

b.py
Copy after login

那么Python如何找到我们定义的module?在标准包sys中,path属性记录了Python的包路径.你可以将之打印出来:

import sys

print sys.path

通常我们可以将module的包路径放到环境变量PYTHONPATH中,该环境变量会自动添加到sys.path属性.另一种方便的方法是编程中直接指定我们的module路径到sys.path 中:

import sys
sys.path.append(&#39;D:\\download&#39;)

from parent.child.a import add_func


print sys.path

print "Import add_func from module a"
print "Result of 1 plus 2 is: "
print add_func(1,2)
Copy after login

总结

    你会发现这个教程相当的简单.许多Python特性在代码中以隐含方式提出,这些特性包括:Python不需要显式声明数据类型,关键字说明,字符串函数的解释等等.我认为一个熟练的程序员应该对这些概念相当了解,这样在你挤出宝贵的一小时阅读这篇短短的教程之后,你能够通过已有知识的迁移类比尽快熟悉Python,然后尽快能用它开始编程.

    当然,1小时学会Python颇有哗众取宠之嫌.确切的说,编程语言包括语法和标准库.语法相当于武术招式,而标准库应用实践经验则类似于内功,需要长期锻炼.Python学习了Java的长处,提供了大量极方便易用的标准库供程序员"拿来主义".(这也是Python成功的原因),在开篇我们看到了Python如何调用Windows cmd的例子,以后我会尽量写上各标准库的用法和一些应用技巧,让大家真正掌握Python.

    但不管怎样,至少你现在会用Python代替繁琐的批处理写程序了.希望那些真的能在一小时内读完本文并开始使用Python的程序员会喜欢这篇小文章,谢谢!

相关推荐:

python入门教程之列表操作

一篇不错的Python入门教程

简洁的十分钟Python入门教程



The above is the detailed content of Python introductory tutorial: Learn Python in 1 hour in detail_python. For more information, please follow other related articles on the PHP Chinese website!

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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles