Python3 is simple but not bad

Source: Internet
Author: User
Tags javascript array
Python is already version 3.1. please refer to the previous article for more information about how to update the tutorial. 2.5 or 2.6. This article is suitable for programmers with Java programming experience to quickly familiarize themselves with Python
This program passed the test on windows xp + python3.1a1.
The idle mentioned in this article refers to the python shell, that is, the IDLE (python gui) you see in the menu after installing python)
In idle, ctrl + n can open a new window. after entering the source code, ctrl + s can be saved. f5 runs the program.
When a new window is opened, ctrl + n is used.
1 Hello

The code is as follows:


# Open a new window and enter:
#! /Usr/bin/python
#-*-Coding: utf8 -*-

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


Knowledge Point:
* Input ("a string") function: displays "a string" and waits for user input.
* Print () function: how to print.
* How to apply Chinese characters
* How to use Multiline comments
'''

2 String and number
But interestingly, in javascript, we may take it for granted to connect strings and numbers, because it is a dynamic language, but it is a bit strange in Python, as shown below:

The code is as follows:


#! /Usr/bin/python
A = 2
B = "test"
C = a + B


An error occurs when you run this line of program, prompting you that the string and number cannot be connected, so you have to use the built-in function for conversion.

The code is as follows:


#! /Usr/bin/python
# An error occurs when you run this line of program, prompting you that the string and number cannot be connected, so you have to use the built-in function for conversion.
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 Point:
* Use the int and str functions to convert strings and numbers.
* Print the name starting with # instead of the habit //
* How to print multiple parameters
'''

3 List

The code is as follows:


#! /Usr/bin/python
#-*-Coding: utf8 -*-
# List is similar to the Javascript array for ease of use
# Define tuples
Word = ['A', 'B', 'C', 'D', 'e', 'e', 'F', 'G']
# How to access elements in tuples through indexes
A = word [2]
Print ("a is:" +)
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 tables t the last two characters
L = len (word)
Print ("Length of word is:" + str (l ))
Print ("Adds new element ")
Word. append ('h ')
Print (word)
# Deleting an element
Del word [0]
Print (word)
Del word [1: 3]
Print (word)
'''


Knowledge Point:
* The List length is dynamic. you can add or delete any element.
* Using indexes can easily access elements and even return a sublist
* For more methods, see The Python documentation.
'''

4. dictionary

The code is 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 Point:
* Use it as a Java Map.
'''

5 String
Compared with C/C ++, the Python method for processing strings is very touching. use strings as a list.

The code is as follows:


#! /Usr/bin/python
Word = "abcdefg"
A = word [2]
Print ("a is:" +)
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 character t the last two characters
L = len (word)
Print ("Length of word is:" + str (l ))


Is the length of a Chinese character string the same as that of an English character string?

The code is 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 Point:
Similar to Java, all strings in python3 are unicode, so the length is consistent.

6. condition and loop statements

The code is as follows:


#! /Usr/bin/python
# Condition and loop statements
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', 'deletestrate']
For x in:
Print (x, len (x ))
# Knowledge Point:
# * Condition and loop statements
# * How to obtain console input


7 functions

The code is 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)
A good function
#! /Usr/bin/python
#-*-Coding: utf8 -*-
# The range () function
A = range (1, 10)
For I in:
Print (I)
A = range (-2,-11,-3) # The 3rd parameter stands for step
For I in:
Print (I)


Knowledge Point:
Python does not need to use {} to control the program structure. it forces you to use indentation to write programs, so that the code is clear.
Easy to define functions
Easy-to-use range functions

8. Exception handling

The code is as follows:


#! /Usr/bin/python
S = input ("Input your age :")
If s = "":
Raise Exception ("Input must no be empty .")
Try:
I = int (s)
Except t Exception as err:
Print (err)
Finally: # Clean up action
Print ("Goodbye! ")


9. file processing
Compared with Java, python text processing is even more touching.

The code is 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 ("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 in each row is: % s" % line)
F. close ()


Knowledge Point:
Open parameter: r indicates reading, w indicates writing data. before writing, clear the file content. a opens and attaches content.
Close the file after it is opened.

Class 10 and inheritance

The code is 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 Point:
* Self: similar to Java's this parameter
'''


11-pack mechanism
Each. py file is called a module, and modules can be imported to each other. See the following example:

The code is as follows:


# A. py
Def add_func (a, B ):
Return a + B
# B. py
From a import add_func # Also can be: import
Print ("Import add_func from module ")
Print ("Result of 1 plus 2 is :")
Print (add_func (1, 2) # If using "import a", then here shocould be "a. add_func"


The module can be defined in the package. the Python definition package method is a little odd. Suppose we have a parent folder, which has a child subfolder. child has a module. py. how to let Python know the file hierarchy? A file named _ init _. py is put in each directory. the file content can be empty. the hierarchical structure is as follows:
Parent
-- _ Init _. py
-- Child
-- _ Init _. py
-- A. py
B. py
So how does Python find the module we define? In the standard package sys, the path property records the Python package path. you can print it out:
Import sys
Print (sys. path)
Generally, we can put the module package path in the environment variable PYTHONPATH, which will be automatically added to sys. path attribute. another convenient method is to specify the module path directly to sys in programming. path:

The code is 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 ")
Print ("Result of 1 plus 2 is :")
Print (add_func (1, 2 ))


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


12 built-in help Manual
Compared with C ++, Java's outstanding progress is the built-in Javadoc mechanism. programmers can read Javadoc to learn about function usage. Python also has built-in convenience functions for programmers to refer.

Dir function: view the methods of a class/object. if a method cannot be thought of, try dir (list) in idle)
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.