Python3 Introductory Tutorials Simple but relatively good _python

Source: Internet
Author: User
Tags exception handling in python
This article is suitable for programmers with Java programming experience to quickly familiarize themselves with Python
This procedure is passed in the Windows XP+PYTHON3.1A1 test.
The idle referred to in this article refers to the Python shell, the idle (Python GUI) that you see in the menu after you install Python
In Idle CTRL + N can open a new window, input source code after ctrl+s can save, F5 run the program.
Any opening of a new window means CTRL + N operation.
1 Hello
Copy Code code as follows:

#打开新窗口, enter:
#! /usr/bin/python
#-*-Coding:utf8-*-

S1=input ("Input your Name:")
Print ("Hello,%s"% s1)
'''

Knowledge Points:
* Input ("a string") function: Display "A string", and wait for user input.
The * print () function: how to print.
* How to apply Chinese
* How to use multiple lines of comment
'''

2 Strings and Numbers
But interestingly, in JavaScript we would ideally connect strings to numbers, because it's a dynamic language. But it's a little weird in Python, as follows:
Copy Code code as follows:

#! /usr/bin/python
a=2
b= "Test"
C=a+b

Running this line of programs will make an error, prompting you that strings and numbers can't be connected, so you have to use built-in functions to convert
Copy Code code as follows:

#! /usr/bin/python
#运行这行程序会出错, it prompts you that strings and numbers cannot be connected, so you have to convert them with built-in functions
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 Points:
* Convert strings and numbers using the INT and STR functions
* Print to start with #, not used//
* How to print multiple parameters
'''

3 List
Copy Code code as follows:

#! /usr/bin/python
#-*-Coding:utf8-*-
#列表类似Javascript的数组, convenient and easy to use
#定义元组
Word=[' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' G '
#如何通过索引访问元组里的元素
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) # 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)
#删除元素
Del Word[0]
Print (word)
Del Word[1:3]
Print (word)
'''

Knowledge Points:
* The list length is dynamic and you can add any deletion elements.
* Index makes it easy to access elements and even returns a child list
* More methods Please refer to the Python documentation
'''

4 Dictionaries
Copy Code code as follows:

#! /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 Points:
* Use him as a map of Java.
'''

5 string
It's so much more impressive than the way C/c++,python handles strings. Use a string as a list.
Copy Code code as follows:

#! /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 two characters
L=len (Word)
Print ("Length of Word is:" + str (l))

is the string length the same in Chinese and English?
Copy Code code as follows:

#! /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 Points:
Like Java, all strings in Python3 are Unicode, so they are consistent in length.

6 Conditions and circular statements
Copy Code code as follows:

#! /usr/bin/python
#条件和循环语句
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))
#知识点:
# * Conditions and looping statements
# * How to get the console input

7 function
Copy Code code as follows:

#! /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)
An easy to use 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 Points:
Python does not use {} to control the structure, he forces you to write the program with indentation, so that the code is clear.
Defining functions is convenient and simple
Convenient and easy to use range function

8 Exception handling
Copy Code code as follows:

#! /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
Contrast Java,python text processing once again makes people moved
Copy Code code as follows:

#! /usr/bin/python
Spath= "D:/download/baa.txt"
F=open (spath, "W") # opens file for writing. Creates this file doesn ' t exist.
F.write ("The 1.\n")
F.writelines ("the 2.")
F.close ()
F=open (spath, "R") # opens file for reading
For line in F:
Print ("Data for each row is:%s"%line)
F.close ()

Knowledge Points:
Open parameter: R means read, W writes data, clears the contents of the file before writing, a opens and appends the content.
Remember to close after opening file

10 Classes and inheritance
Copy Code code as follows:

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 Points:
* Self: Java-like this parameter
'''

11 Packet mechanism
Each. py file is referred to as a module,module between each other. Please refer to the following examples:
Copy Code code as follows:

# 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 to be ' a.add_func '

Module can be defined inside the package. The way Python defines a package is a little odd, assuming we have a parent folder that has a child subfolder. There is a module a.py. How do you let Python know about this file hierarchy? very simply, each directory has a file named _init_.py. The contents of the file can be empty. This hierarchy looks like this:
Parent
--__init_.py
--child
--__init_.py
--a.py
b.py
So how does python find the module we defined? In standard package SYS, the Path property records the Python package path. You can print it out:
Import Sys
Print (Sys.path)
In general, we can place the package path of module into the environment variable Pythonpath, which is automatically added to the Sys.path property. Another convenient approach is to programmatically specify our module path to the Sys.path:
Copy Code code as follows:

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 Points:
How to define modules and packages
How to add module paths to the system path so that Python can find them
How to get the current path


12 Built-in Help Manual
The highlight of the contrast C++,java is the built-in Javadoc mechanism, where programmers can read Javadoc to learn about functional usage. Python also built some handy functions for programmers to refer to.

Dir function: View the method of a class/object. If there is a way to remember, knock on Dir. In Idle, try Dir (list)
Help function: Detailed class/object introduction. In Idle, try Help (list)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.