One hour quick start Python tutorial

Time:2022-7-30
catalogue
  • Why use Python
  • Python applications
  • Hello world
  • Internationalization support
  • Easy to use calculator
  • String, ASCII and Unicode
  • Use list
  • Conditional and circular statements
  • How to define functions
  • File i/o
  • exception handling
  • Classes and inheritance
  • Package mechanism
  • summary

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 ranges from 192.168.0.101 to 192.168.0.200
Idea: program with shell. (Linux is usually Bash and windows is batch script) For example, on windows, use the Ping IP command to test each machine in turn and get the console output Since the console text is usually “reply from…” when Ping is connected and “time out…” when Ping is not connected, you can know whether the machine is connected by searching the string in the result
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();
}

This code works well. The problem is that in order to run this code, you need to do some extra work. These extra work include:

  • Write a class file
  • Write a main method
  • Compile it into byte code
  • Since byte code cannot be run directly, you need to write a small bat or bash script to run it

Of course, using c/c++ can also complete this work. But c/c++ is not a cross platform language In this simple enough example, you may not see the difference between c/c++ and Java implementation, but in some more complex scenarios, such as recording the connectivity information to the network database. Because the network interface implementation methods of Linux and windows are different, you have to write two function versions. There is no such concern with 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()

Compared with Java, the implementation of Python is simpler and your writing time is faster. You don’t need to write the main function, and this program can be run directly after saving. In addition, like Java, Python is also cross platform

Experienced c/java programmers may argue that writing in c/java will be faster than writing in Python. There are different opinions on this point My idea is that when you master Java and python at the same time, you will find that the speed of writing such programs in Python is much faster than that in Java. For example, when operating local files, you only need one line of code without many stream wrapper classes in Java. Various languages have their natural application scope. It is the most time-saving and labor-saving to use Python to deal with some short programs, such as interactive programming with the operating system

Python applications

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

Hello world

After installing python (my native version is 2.5.4), open idle (Python GUI), which is the python language interpreter, and the statements you write can run immediately. Let’s write a famous program statement:


print "Hello,world!"

And press enter. You can see this famous saying introduced by k&r into the program world

Select “file” – “new window” in the interpreter or press ctrl+n to open a new editor. Write the following statement:


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

Save it as a.py file. Press F5, and you can see the running results of the program. This is the second running mode of Python

Find the a.py file you saved and double-click it. You can also see the program results. Python programs can run directly, which is an advantage over Java

Internationalization support

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

Print "welcome to Olympic China!" 
raw_input("Press enter key to close this window!");

When you save the code, python will prompt you whether to change the character set of the file. The results are as follows:

# -*- coding: cp936 -*-
Print "welcome to Olympic China!" 
raw_input("Press enter key to close this window! ");

Change the character set to a more familiar form:

# -*- coding: GBK -*-

Print "welcome to Olympic China!"# Examples of using Chinese 
raw_input("Press enter key to close this window");

The program works well

Easy to use calculator

It’s too troublesome to count with the calculator provided by Microsoft. Open the Python interpreter and calculate directly:


a=100.0 
b=201.1 
c=2343 
print (a+b+c)/c 

String, ASCII and Unicode

You can print out a string of predefined output formats as follows:


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

How are strings accessed? Look at 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)

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'm sorry we should use unicode char!Characters number of your Chinese \  name in unicode is:"+str(l);

Use list

Similar to list in Java, this is a convenient data type:

word=['a','b','c','d','e','f','g']
a=word[2]
print "a is: "+a
b=word[1:3]
print "b is: " print b # index1 and 2 elements of word.
c=word[:2]
print "c is: " print c # index0 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 # index3 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[image-b4ced-1616074265420-0]" word.append ('H')
print word

Conditional and circular 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= ['cat', 'window', 'defenestrate'] for x ina:
    print x, len(x) 

How to define functions


# 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

In addition, a convenient function is introduced:


# 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

File i/o


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

f.close()

f=open(spath,"r") # Opens file forreading for line in f:
    print line

f.close()

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!"

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)

Package mechanism

Each.Py file is called a module, and modules can be imported into each other. Please refer to the following examples:


# a.py
def add_func(a,b):
    return a+b

# 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"

Module can be defined in the package Python defines packages in a slightly strange way. Suppose we have a parent folder with a child subfolder There is a module a.py in child. How can Python know this file hierarchy? Very simple, each directory has a name called_ init_. Py. The contents of this file can be empty. This hierarchy is as follows:

parent
  –__init_.py
  –child
    — __init_.py
    –a.py

b.py

So how does Python find the module we defined? In the standard package sys, the path attribute records the package path of Python. You can print it out:


import sys

print sys.path

Usually, we can put the package path of the module into the environment variable pythonpath, which will be automatically added to the sys.path attribute. Another convenient method is to directly specify our module path to sys in programming In path:


import sys
sys.path.append('D:\\download')

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)

summary

This tutorial is very simple, which contains many Python features exposed in the code, including Python does not need to explicitly declare data types, keyword descriptions, string function interpretation, etc. through this article, you can get familiar with Python as soon as possible, and then use it to start programming as soon as possible

Recommended Today

JS generate guid method

JS generate guid method https://blog.csdn.net/Alive_tree/article/details/87942348 Globally unique identification(GUID) is an algorithm generatedBinaryCount Reg128 bitsNumber ofidentifier , GUID is mainly used in networks or systems with multiple nodes and computers. Ideally, any computational geometry computer cluster will not generate two identical guids, and the total number of guids is2^128In theory, it is difficult to make two […]