Python3 tutorial is simple but good

  • 2020-04-02 09:30:02
  • OfStack

This article is for programmers with Java programming experience to quickly become familiar with Python
This program in Windows xp+python3.1a1 test passed.
Idle mentioned in this article refers to the python shell, that is, the idle (python GUI) that you see in the menu after installing python.
In idle, CTRL +n can open a new window, enter the source code after CTRL +s can save,f5 run the program.
Opening a new window means CTRL +n.
1 hello
 
# Open a new window , The input : 
#! /usr/bin/python 
# -*- coding: utf8 -*- 

s1=input("Input your name:") 
print(" hello ,%s" % s1) 
''' 

Knowledge:
* input(" some string ") function: displays "some string" and waits for user input.
* print() function: how to print.
* how to use Chinese
* how to use multi-line comments
' ' '

2 strings and Numbers
But the interesting thing is that in javascript we would ideally link strings to Numbers, of course, because it's a dynamic language, but in Python it's a little weird, like this:
 
#! /usr/bin/python 
a=2 
b="test" 
c=a+b 

Running this line of code causes an error that tells you that strings and Numbers cannot be connected, so you have to use the built-in function to convert
 
#! /usr/bin/python 
# Running this line will cause an error , The string and the number cannot be connected , So you have to use the built-in function to transform  
a=2 
b="test" 
c=str(a)+b 
d="1111" 
e=a+int(d) 
#How to print multiply values 
print ("c is %s,e is %i" % (c,e)) 
''' 

Knowledge:
* converts strings and Numbers using the int and STR functions
* printing begins with #, not the customary //
* how to print multiple parameters
' ' '

3 a list
 
#! /usr/bin/python 
# -*- coding: utf8 -*- 
# The list of similar Javascript An array of , Convenient and easy to use  
# Define a tuple  
word=['a','b','c','d','e','f','g'] 
# How do I access elements in a tuple by index  
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. 
# Tuples can be merged  
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('h') 
print (word) 
# Remove elements  
del word[0] 
print (word) 
del word[1:3] 
print (word) 
''' 

Knowledge:
* the list length is dynamic and you can add and remove elements at will.
* indexes make it easy to access elements or even return a sublist
* refer to the Python documentation for more methods
' ' '

4 a dictionary
 
#! /usr/bin/python 
x={'a':'aaa','b':'bbb','c':12} 
print (x['a']) 
print (x['b']) 
print (x['c']) 
for key in x: 
print ("Key is %s and value is %s" % (key,x[key])) 
''' 

Knowledge:
* use it as a Java Map.
' ' '

5 string
The way Python handles strings is more impressive than C/C++. Use strings as lists.
 
#! /usr/bin/python 
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)) 

Are Chinese and English strings the same length?
 
#! /usr/bin/python 
# -*- coding: utf8 -*- 
s=input(" Enter your Chinese name , Press enter to continue "); 
print (" Your name is  : " +s) 
l=len(s) 
print (" The length of your Chinese name is :"+str(l)) 

Knowledge:
Similar to Java, in python3 all strings are unicode, so they have the same length.

6. Conditions and loops
 
#! /usr/bin/python 
# Conditions and loops  
x=int(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 in a: 
print (x, len(x)) 
# knowledge : 
# *  Conditions and loops  
# *  How do I get console input  

7 function
 
#! /usr/bin/python 
# -*- coding: utf8 -*- 
def sum(a,b): 
return a+b 

func = sum 
r = func(5,6) 
print (r) 
#  Provide default values  
def add(a,b=2): 
return a+b 
r=add(1) 
print (r) 
r=add(1,5) 
print (r) 
 A nice function  
#! /usr/bin/python 
# -*- coding: utf8 -*- 
# The range() function 
a =range (1,10) 
for i in a: 
print (i) 
a = range(-2,-11,-3) # The 3rd parameter stands for step 
for i in a: 
print (i) 

Knowledge:
Python doesn't use {} to control the program structure. It forces you to indent the program to make the code clear.
It's easy to define functions
Handy range function

8 exception handling
 
#! /usr/bin/python 
s=input("Input your age:") 
if s =="": 
raise Exception("Input must no be empty.") 
try: 
i=int(s) 
except Exception as err: 
print(err) 
finally: # Clean up action 
print("Goodbye!") 

9 file processing
In contrast to Java,python's text handling is again impressive
 
#! /usr/bin/python 
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 for reading 
for line in f: 
print(" The data for each row is :%s"%line) 
f.close() 

Knowledge:
Open parameter :r for read,w for write, empty file contents before write,a open and append contents.
Remember to close the file when you open it

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)) 
''' 
 knowledge : 
* self: similar Java the this parameter  
''' 

11 package mechanism
Each.py file is called a module, and modules can be imported into each other.
 
# 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" 

Python defines packages in a slightly odd way, assuming that we have a parent folder that has a child folder that has a module a.p. in the child. Simply, each directory contains a file named _init_.py. The contents of the file can be empty.
The parent
-- __init_. Py
- the child
-- __init_. Py
- Amy polumbo y
P. y.
So how does Python find the module we've defined? In the standard package sys, the path property records the Python package path. You can print it out:
The import sys
Print (sys. Path)
In general, we can place the package path of our module in the environment variable PYTHONPATH, which will be automatically added to the sys.path property.
 
import sys 
import os 
sys.path.append(os.getcwd()+'\parent\child') 
print(sys.path) 
from 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)) 

Knowledge:
How do I define modules and packages
How do I add module paths to system paths so that python can find them
How do I get the current path


Built-in help manual
Java's outstanding improvement over C++ is the built-in Javadoc mechanism, which allows programmers to read Javadoc for function usage.Python also has built-in convenience functions for programmers to refer to.

Dir: a method to view a class/object. If you can't remember a method, type dir. In idle, try dir(list)
In idle, try help(list)

Related articles: