Python basic syntax

Source: Internet
Author: User
Tags logical operators types of functions ticket

What is the origin of Python?
Interpreter and compiler differences?
What is the difference between a compiled language and an interpreted language?
The first Python program
Write only one code statement per line
No spaces in front of each line of code
PYTHON2.0 interpreter does not support Chinese
python3.0 Support Chinese
How do I interactively execute a python program? Python Python3
How do you mean the second party in Python? **
Installation of Pycharm? Direct decompression can be used to move it to the OPT directory for other people to use
0. Construction of the environment
1. Output string
Print ("Hello haha")
command followed by the execution of the py file to run the script
Python2
Python3
Interactive mode (command line input the following command enters interactive mode)
Ipython2
Ipython3
2. Notes
Single-line Comment
#
Multi-line comments
‘‘‘
Print ("Hello World")
Print ("Hello World")
Print ("*", end= "")
‘‘‘
3. Define the variable (no need to define the type Python will automatically determine))
Score = 100
Variable type
Number (numeric)
int integer, Python2 int and long python3 only int
Float floating point number,
BOOL Boolean type
String (String)
List (lists)
Tuple (tuple)
Sets (collection)
Dictionary (dictionary)

4. Input statements
High = input ("Please enter your height:")
Note: Python3 takes everything entered as a string to the variable
Python2 take what you've entered as code execution, like name as a variable
Use Raw_input ("ddd") to achieve the same effect in Python2
5. Use of placeholders
Age = 18
Print ("The value in the age variable is%d"%age)
Name = "Brother Dong"
Print ("Name is:%s"%name)
Chinese processing of 6.python2 and Python3
Python3 Support Chinese
Python2 if the comment or code in the Chinese language, then execution will be error
Workaround: At the beginning of the code, add
#_ *_ coding:utf-8 _*_ (recommended)
#coding =utf-8
7. Judgment syntax:
If name<18:
Code 1
Code 2
Pass means the code here is just temporarily empty.
Else
Code 4
Code 5
Code 6
Note that code with four spaces before the code is subject to If--else moderation,
Code 6 because there is no space, he will execute whether the condition is met or not.
8. INPUT type Conversion
Age = input () Gets the value that the user entered is a string if necessary to
It becomes a different type, such as int, which you can do
Age = Input ()
Age_num=int (age)
age_num = Int (input ("Please enter your Age:"))
9. Output multiple values at once
Print ("Name is:%s, age is:%d, address is:%s"% (name, ages, addr))
10. Special Operators
5/2=2.5
7//2=3 Pick up Business
7%2=1 to take the remainder
"ABC"
Output: ABCABC
2**3=8 Power

Comparison operators
<,>,<=,>=,!=
logical operators
And, OR,
VI File name +11 edit 11 lines
Not represents the negation of the condition
If not (A>0 and a<=50):
Print ("Between 0 and 50 ....")
11.if-elif usage
Sex = input ("Please enter your Gender:")
if sex = = "Male":
Print ("You are male, you can have a beard ....")
elif sex = = "female":
Print ("You are a female, can stay long hair ...")
#elif sex = = "neutral":
Else
Print ("You are the 3rd gender, do what you want ...")
12.while usage
While i<=100:
Print ("%d"%i) #print (i)
i = i+1
Nesting of 13.if-else
#先判断是否有车票
If ticket==1:
Print ("Pass the ticket inspection, into the station, next to Security")
#判断刀的长度是否合法
If knifelenght<=10:
Print ("Through the security check, into the waiting Room")
Print ("Soon to see TA, very happy ...")
Else
Print ("Security has not passed, waiting for police to deal with ....")
Else
Print ("Brother you have not bought a ticket, first go to buy a ticket to stop ...")
14.while nesting
I=1
#用来控制行数 (Print rectangle)
While i<=5:
#用来控制每一行中的列数
j = 1
While j<=5:
Print ("*", end= "")
#j = the way to let J plus 1 in j+1#c language: j + +; ++j; J+=1; j=j+1;
J+=1
Print ("")
i = i+1
Print ("*", "end=") prints the default line wrap, followed by end to make it non-wrapped
15. Compound assignment operator
A+=1------------>j=j+1
A-=1,a*=1,a/=1,a%=1,a//=1
Get a random number of 0-2
Computer = Random.randint (0,2)
Break to jump out of a loop
Continue used to skip this cycle.
The scope of break in a while loop nesting: works only with the nearest while
16. How strings are stored in memory
One-byte storage maximum value of 255
The number 110 can be stored in a single byte
"110" must be four bytes each character at the end of one byte plus "" "in Python can not count
STR (110) can be converted to a string by a number
Len (variable) can look at the number of bytes that the variable occupies
17. Two ways to compose a string
One, the + number on both sides of the string is the combination of strings, there is a number on both sides of a numeric combination is a number
Two, F = "====%s===="% (a+b)
18. subscripts and slices
The letters in the Name= "Abcdefghijk" string have been labeled starting from 0.
NAME[2] You can remove the C
Name[-1] can remove K
Slice (take one piece)
Name[2:6] will take out the CDE (Baotou does not wrap the tail)
Name[2:-1] from the third one to the second from the bottom
Name[2:] Take to the end
Name[2:-1:2] Jump, that is, the last representative step Cegi
Name[::-1] Reverse the string
19. String Common operations
Mystr= "Dajsi aaadfe jfieiwejijojeei"
MyStr. Enter to view all string operations (interactive mode)
Mystr.find ("AA") returns 6 that is the first letter of the subscript, cannot find the return-1
Mystr.rfind ("AA") find the first one from the rear
Mystr.index ("AA") found the return subscript, could not find the return exception exception exception!!!
Mystr.rindex ("AA") found the return subscript, could not find the return exception exception exception!!!
Mystr.count ("AA", Start=0,end=len (MYSTR)) returns the number of characters that appear
Mystr.replace ("A", "a", 1,) Replace a in a string with a, the third parameter is replaced by several here first A is substituted
Mystr.split ("") parameter for what to cut, nothing to add by default by space and/t all cut off
Mystr.splitline () cut by row/n
Mystr.capitallize () Capitalize first letter of Word
Mystr.title () capitalize the first letter of each word
Mystr.startwith ("a") is not what begins with the return value of TRUE or flase
Mystr.endwith (". txt") is not the end of what
Mystr.lower () Convert lowercase
Mystr.upper () Convert uppercase
Mystr.ljust (50) Align Left
Mystr.rjust (50) Align Right
Mystr.centet (50) Center alignment
Mystr.lstrip () Clear left space
Mystr.rstrip () Clear the right space
Mystr.strip () Clear left and right spaces
Mystr.partition ("AAA") looking for AAA split from left
Mystr.isalpha () is the letter return True
Mystr.isdigit () is a number that returns True
Mystr.isalnum () both letters and numbers return true
Mystr.isspace () to determine if it is a pure space
"=". Jone (Liebiao) connect the elements of the list with =
20. List
Defined
name = ["Lao Wang", "Lao Li", "Lao du", 3.14], can store multiple data types
Operation (Increase and deletion of check)
Increase: Name.append ("Goku") at the end of the add
Name.insert (0, eight commandments) is added at the location labeled 0
Name1.extend (name2) merges two lists,
Name1+name2 Merge two lists,
Delete: Name.pop () Delete last element
Name.remove ("Lao Li") according to the content of the deletion, from the go after only delete a
Del Name[3]
Change: name[0] = "Early morning" modifies the specified subscript element
Check: "Lao Zhao" in name to determine whether Lao Zhao in the name list
"Lao Zhao" not in name
21. Dictionaries
Defined:
infor = {"Name": "Occupy Mountain", "QQ": "17", "Key 3": "Value 3"}
The list can be nested in a dictionary
name=[{"name": "Mountain"} {"QQ": "17"} {"name": "Shandong"}]
name["name"] take out all the names
Dictionary operations
Add: infor[age1]=18
Delete: del infor["name"]
Change: infor[name]= "SS"
Check: infor["QQ" not reported abnormal
Infor.get ("QQ") did not report abnormal
Application of 22.for-else
For V in V
Pass
Else
Pass
23. Extend and append of the list
a=[1,2]
B=[22,11]
A.extend (b)--->[1,2,22,11]
A.append (b)--->[1,2,[22,11]]
24. Common Dictionary Operations
info={"name": "Occupy Mountain", "QQ": "17", "Key 3": "Value 3"}
Len (info) is measured as the length of the key-value pair
In Python2
Info.keys () gets all the keys in the dictionary and returns a list
Info.value () gets all the values in the dictionary, returns the value as a list
The object returned in the Python3
Info.keys () return value is----->dict_keys ([mame,age])
Info.items () Get the key and the worthy tuple package in the list of lists put in the tuple
Dict_keys ([("Mame", "La"), ("Age", 12)])
Split Package

24. Tuples
Definition: a= (+/-)
Tuples and lists are similar but tuples are not modifiable, but you can use connectors
Type (a) =tuple;
To delete a tuple:
Del A
Unpacking of tuples:
A= (a)
D,b,c = a--->d=1;b=2;c=3
Tuple (list) to convert tuples to lists
Note: If only one value (1,) is called a tuple
25. Definition of functions
Sublime Tips Select ctrl+d You can edit multiple lines ctrl+--> jump directly to the end of the line
Defining functions
def variable name ():
Code One
Code two
Function call
Variable name ()
Multiple function definitions can be arbitrarily called, regardless of the order of the definition
Defining a function with parameters
DEF variable name (A, B)
Statement One
Statement Two
function with fan return
DEF variable name (A, B)
Statement One
Statement Two
C=22
Return C
A function with multiple return returned values
Syntax error-free, but only returns the first value other return will not execute because the function is over
However, multiple values can be encapsulated in tuples, which can be returned in a list.
Four types of functions:
No parameter no return, no parameter has a return value, there is a parameter return value, there are parameters no return value
Nested calls to functions
Def print_line ():
Print ("-" *50)

Def print_5_line ():
i = 0
While i<5:
Print_line ()
I+=1

Print_5_line ()
26. Local variables and global variables
Local variables
A variable defined in a function that works only within this function, called a local variable
Global variables
Variables defined before a function is defined or called
The difference between a local variable and a global variable
#定义一个全局变量, Wendu
Wendu = 0

Def get_wendu ():
#如果wendu这个变量已经在全局变量的位置定义了, you also want to modify this global variable in the function.
#那么 just wendu= a value that's not enough,,, this variable is a local variable, just the name of the global variable.
#相同罢了
#wendu = 33

#使用global用来对一个全局变量的声明, the wendu=33 in this function is not to define a local variable, but
#对全局变量进行修改
Global Wendu
Wendu = 33

Def print_wendu ():
Print ("Temp is%d"%wendu)

Get_wendu ()
Print_wendu ()
Attention:
The global variable must be placed before the function call,
Global variable naming recommended prefixes avoid the same as local variables
Function Documentation Description
Help (print) to see the description of the function document
The first line of the function adds the following format to add a document description
"" Displays all business card information "" "
Lists and dictionaries can be used as global variables in functions without adding globle
Return 14,13 Returns a tuple (14,13)
27. Default parameters
def test (a,d,b=22,c=33):
Print (a)
Print (b)
Print (c)
Print (d)

Test (D=11,A=22,C=44)
Test (11,22,33)
Indefinite length parameter
def sum_2_nums (A,b,*args):
Print ("-" *30)
Print (a)
Print (b)
Print (args)

result = A+b
For num in args:
Result+=num
Print ("result=%d"%result)

Sum_2_nums (11,22,33,44,55,66,77)
Sum_2_nums (11,22,33)
Sum_2_nums (11,22)
#sum_2_nums (one) #错误 because at least 2 arguments in the formal parameter

def test (A,b,c=33,*args,**kwargs): #在定义的时候 *,** to indicate that the following variables have special functions
Print (a)
Print (b)
Print (c)
Print (args)
Print (Kwargs)

#test (11,22,33,44,55,66,77,task=99,done=89)
A = (44,55,66)
B = {"Name": "Laowang", "Age": 18}
The test (11,22,33,a,b) output is not the same as the bottom line
Test (11,22,33,*a,**b) #在实参中 *,** means unpacking a meta-ancestor/dictionary
Test (name= "DD") extra arguments are saved to the tuple *args, key-value pairs are saved to **kwargs
28. References
ID (variable) to get the address where the variable is saved
A = 100
b = A gives the address of a to B instead of the value of a, which is called a reference.
Note: Python will automatically clean up if the variable reference is missing.
29. mutable type, immutable type
string is immutable type
Only lists and dictionaries are mutable
mutable types may not be associated with the hash algorithm when the key value causes
30.NUM=[1,2,66,33,55] Sort
Num.sort () default small to large sort
Num.sort (reverse=true) sort from large to small
Sort the dictionary
Num.reservice () Reverse infors = [{' Name ': ' Laowang ', ' age ': 10},{' name ': ' Xiaoming ', ' age ': 20},{' name ': ' Banzhang ', ' Age ': 10} ]
Infors.sort (Key=lambda x:x[' age ')
31. Anonymous functions
Test2 = Lambda a,b:a+b
RESULT2 = Test2 (11,22) #调用匿名函数
The use of eval: You can put the input in the Python3, from the string into other functions, positive numbers and so on.
#python2中的方式
#func_new = input ("Please enter an anonymous function:")
#python3中的方式
Func_new = input ("Please enter an anonymous function:")
Func_new = eval (func_new)
32. How to Exchange two variables
A = 4
b = 5
#第1种
#c = 0
#c = A
#a = b
#b = C
#第2种
#a = A+b
#b = A-B
#a = A-B
#第3种 (Python exclusive)
A, B = b,a
Print ("a=%d,b=%d"% (A, b))
There is no value pass in 33.python, it is all reference
#a = 100
A = [100]
def test (num):
#num +=num# + = indicates who the NUM is pointing to, and if num points to [100] then it becomes [100,100]
The #如果num points to 100 because 100 is immutable and cannot be modified, so num=num+num
num = num+num#===>[100] + [[+] ====>[100,100] Note as long as the num=xxx must be num points to a new place
Print (num)
Test (a)
Print (a)
34. Documents
Write
f = open ("Xxx.txt", "W")
F.write ("hahaha")
F.close ()
Read
f = open ("Xxx.txt", "R")
Content = F.read ()
Print (content)
F.close ()
F.read (num) reads num bytes at a time
F.readline () reads one line at a time, returns a string
F.readlines () reads one line at a time, encapsulates it in the list, returns the list
File name processing
#test. py-----> test[Copy].py
#new_file_name = "[Copy]" +old_file_name
Position = Old_file_name.rfind (".")
New_file_name = old_file_name[:p osition] + "[Copy]" + old_file_name[position:]
35. File positioning and Reading

f = open ("A.txt", "R")
F.seek (A, B)
A indicates the number of bytes skipped positive to the right, negative to the left, Python3 does not support negative numbers
B has three values 0 file start
1 File Current Location
2 End of File
Import OS
Os.rename ("Old file name", "New file name")
Os.remove ("File name")
Os.mkdir ()
Os.rmdir ()
OS.GETCWD ()
Os.chdir ()
Os.listdir ()
36. Definition of a class
Class Cat:
#属性

#方法
Def eat (self):
Print ("Cat is eating fish ....")

def drink (self):
Print ("Cat is drinking Kele ...")

Create an Object
Tom = Cat ()
Calling Object methods
Tom.eat ()
Adding properties to an object
Tom.name = "Tom"
Tom.age = 40
Getting the properties of an object
Print ("Age of%s is:%d"% (Self.name, self.age))
Define a method to put the upper statement into the method
Usage of 37.self
#方法
Def eat (self):
Print ("Cat is eating fish ....")
When you define a method, the incoming self represents the calling object, similar to this in Java
But self is not a keyword that can be replaced with any other character
Usage of __init__.
#初始化对象
def __init__ (self, new_name, new_age):
Self.name = New_name
Self.age = New_age
Lanmao = Cat ("Blue Cat", 10)
39. Ways to create objects
Creating objects
Python automatically calls the Init method
Returns an object reference to a variable
40.__str__ usage (similar to ToString () in Java)
def __str__ (self):
Return "Age of%s is:%d"% (Self.name, self.age)
Print (Tom)
41. Hide Properties
You can not define a property in a class, but outside the Add property
#私有方法.
def __send_msg (self):
Print ("------is sending a text message------")
43.__del__ usage
def __del__ (self):
Print ("-----Heroes over------")
#如果在程序结束时, some objects still exist, so the Python interpreter will
Automatically call their __del__ method to complete the cleanup work
44. Measuring object Reference counting method
Import Sys
Sys.getrefcount (object) returns the number of reference counts
45. Inheritance
#父类
Class Animal:
Def eat (self):
Print ("-----eat----")
#子类 (parentheses into the parent class after the subclass name)
Class Cat (Animal):
#扩展父类功能
def catch (self):
Print ("----catch mouse----")
#重写父类功能
Def eat (self):
Print ("-----eat ah ah ah----")
Calling the overridden method
#第1种调用被重写的父类的方法
#Dog. Bark (self)
#第2种
Super (). Bark ()
Private methods, private properties, performance in inheritance
Private things do not inherit the quilt class
46. Multiple Inheritance
All classes inherit the object class
#新式类在括号里写上object类, Python3 recommended
#经典类不用写, but default inheritance
Class Base (object):
def test (self):
Print ("----Base")

Class A (Base):
def test1 (self):
Print ("-----test1")

Class B (Base):
def test2 (self):
Print ("-----test2")
Class C (A, B):
Pass
Note the point:
If a class inherits multiple classes with the same method name
Print (c.__mro__) can view the class's method invocation order and stop the search if it is found.
47. Class properties and Instance properties
Class is also an object, class properties belong to class objects, and multiple instance objects share class properties
Class Game (object):

#类属性
num = 0

#实例方法
def __init__ (self):
#实例属性
Self.name = "Laowang"

#类方法
@classmethod
def add_num (CLS):
Cls.num = 100

#静态方法
@staticmethod
Def print_menu ():
Print ("----------------------")
Print ("Through FireWire V11.1")
Print ("1. Start the game ")
Print ("2. End Game ")
Print ("----------------------")

Game = Game ()
#Game. Add_num () #可以通过类的名字调用类方法
Game.add_num () #还可以通过这个类创建出来的对象 to call this class method
Print (Game.num)
#Game. Print_menu () #通过类 to call the static method
Game.print_menu () #通过实例对象 to call the static method
Modifying class Properties Game.num=1
Difference: Both the class method and the static method have to pass in the parameter
Static methods do not pass parameters
The use of 48.__new__
#子类重写了new方法则必须调用父类的new方法, otherwise the creation fails
#
Class Dog (object):
def __new__ (CLS): #cls此时是Dog指向的那个类对象
#print (ID (CLS))
Print ("----New Method-----")
Return object.__new__ (CLS)
#print (ID (Dog))
XTQ = Dog ()
49. Single-Case mode
Class Dog (object):
__instance = None

def __new__ (CLS):
if cls.__instance = = None:
Cls.__instance = object.__new__ (CLS)
Return cls.__instance
Else
#return a reference to the last object that was created
Return cls.__instance
50. Initialize only once
Class Dog (object):

__instance = None
__init_flag = False

Def __new__ (CLS, name):
if cls.__instance = = None:
Cls.__instance = object.__new__ (CLS)
Return cls.__instance
Else
#return a reference to the last object that was created
Return cls.__instance

def __init__ (self, name):
if Dog.__init_flag = = False:
Self.name = Name
Dog.__init_flag = True

51. Exception Handling
#coding =utf-8
Try
num = input ("XXX:")
int (num)
#11/0
#open ("Xxx.txt")
#print (num)
Print ("-----1----")

Except (nameerror,filenotfounderror):
Print ("Capture multiple exceptions with tuples .....")
Print ("If you catch an exception after processing ....")
except Exception as RET:
Print ("If Exception is used, this except is bound to capture")
Print (ret)
Else:
As long as the above except does not catch an exception. Print ("function without exception")
Finally:
Print ("------do-----Anyway")

Print ("-----2----")

52. Throwing out a custom exception
Defining exception Classes
Class Networkerror (RuntimeError):
def __init__ (self, arg):
Self.args = arg
Throw a custom exception
Try
Raise Networkerror ("bad hostname")
Except Networkerror,e:
Print E.args

53. Module
A set with a very versatile, is a py file
Import of modules
Import Random
Import xxxxxxxxxxxxxx as SS takes an individual name to the module
RANDOM.__FILE__ will get the module storage path
Calling module contents
Random.xxx ()
From sendmsg import test1
Test1 ()
Mounting module
Sodo pip Install Pygame
Sodo PIP3 Install Pygame
Custom Module Magic Plate
def test1 ():
Pass
def test1 ():
Pass
def main ():
#测试代码
Pass

If __name__== ' __main__ ':
Main ()
The role of 54.__all__
#如果导入这个模块的方式是 from Module name import *, only the names contained in the __all__ list will be imported
__all__ = ["Test1", "Test"]

def test1 ():
Print ("----test-1-----")

Def test2 ():
Print ("----test-2-----")

num = 100

Class Test (object):
Pass
55. Package
Put a lot of py files in a folder, if you set up a __init__.py in the evening clip
Then Python treats it as a package.
Edit this file to add
__all__ = ["AAA"]
The AAA module can be used
Other modules are not referenced in the file can not be used
56. Release and installation of modules
http://blog.csdn.net/qq_29648129/article/details/74852428
57. Sending the program a reference
Import Sys
SYS.ARGV is a list of receive parameters
SYS.ARGV[0] represents the program name
Sys.argv[1] represents the first parameter

Range (10) Returns a list of 0-9
Range (10,18) returns a list of 10-17
Range (10,18,3) 3 stands for Pace, that is, skips the value
Range is risky in py2, and it may not be necessary to consume a large amount of memory
Py3 does not have this problem, because py3 when to use space when generated to you
58. List-Generated
A = [I for I in Range (1,18)]
Results generate a list of 1 to 17
The first I can replace with what list element is what
A = [I for I in range (1,18) if i%2=0]
A = [(i,j) for I in range (3) for I in range (3)]
Results: [(0,0), (0,1), (1,0), (+), (2,0), (2,1)]
59. Collection
F={d,k,d,d,}
F.set (a) Turn a list into a set
List (f) Convert F to List
Collection operation Add Pop remove ...

Python basic syntax

Related Article

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.