In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Today, I would like to share with you the relevant knowledge of what the grammar basis of Python is. The content is detailed and the logic is clear. I believe most people still know too much about this, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.
Python Grammar Basics 01-Python Quick start U1-define variables
Direct definition does not specify the variable type
E.g:
A judgment 10U2-judgment statement # coding=utf-8if s > = 80: print ("excellent") elif s > = 60: print ("good") else: print ("bad")
There must be an indent!
Utf-8 should be emphasized in Chinese.
U3-Loop for i in range (0100): print (I) for i in range (0100): print ("Item {0}" .format (I)) print ("Item {0}, {1}" .format (I, "Hello Python")) U4-definition function def sayHello (): print ("Hello World") def max (a) B): if a > b: return an else: return bsayHello () print (max (2Magne3)) U5-object oriented
Class Hello:
Def sayHello (self): print ("Hello Python") h = Hello () h.sayHello ()
Class Hello:
Def _ init_ (self,name): self._name = namedef sayHello (self): print ("Hello {0}" .format (self._name))
# inherit the Hello class and execute the constructor of the parent class
Class Hi (Hello):
Def _ init_ (self,name): Hello._init_ (self,name) def sayHi (self): print ("Hi {0}" .format (self._name)) h = Hello ("tan") h.sayHello () H2 = Hi ("ther") h2.sayHi () U6-Import python file
1) mylib.py:
Class Hello: def sayHello (self): print ("Hello Python")
2) loadlib.py:
Import mylibh = mylib.Hello () h.sayHello () from mylib import Helloh = Hell0 () h.sayHello () 02-python three advantages, seven features U1-three advantages:
Simple, powerful and object-oriented
U2-Seven Features:
Strict distinction between case and case
Simple, easy to learn, object-oriented
Open source
The library is very rich.
Cross-platform use
Interpretive language
high-level language
U1:Python constants and variables on the basis of 03-python grammar
Constant: the amount that will not be changed while the program is running, but cannot be changed once bound.
To define a constant in Python, you need to create it with the method of an object.
Const.py (to put it under the lib file, lib mainly puts something modular):
# class _ const (object): class ConstError (TypeError): passdef _ setatter__ (self, name, value): if self.__dict__.has_key (name): raise self.ConstError, "Can't rebind const (% s)"% name self.__dict__ [name] = valuedef _ delattr__ (self, name): if name in self.__dict__: raise self.ConstError "Can't unbind const (% s)" name raise NameError, nameimport syssys. Modules [_ _ name__] = _ const () # changliang.py:import constconst.value=5print const.valueconst.value=6
Variable: the amount that can be changed as the program runs, even if assigned.
I = 7print ii = 7print ii + = 1print ii + = 2print iU2:Python number and string five kinds of numbers: int integer type long long integer type, e.g: 878123l float floating point type, e.g: 1.71235 bool Boolean type, e.g: True, False complex complex type, e.g: 3x5j, 2-7j string: use and difference of character set quotation marks enclosed in quotation marks: double quotation marks can be used in single quotation marks And you can output double quotes, but you can use single quotes in them, and you can output three quotes (three single quotes or three double quotes). The contents enclosed in triple quotation marks can be wrapped by escape characters\: will not parse single quotation marks in single quotation marks or double quotation marks in double quotation marks e.g: print'It\'s a dogquotation'\ n: change the line e.g: print "hello tan\ nhello tan" natural string: in python, if our string even has escape characters We also need to leave him as is without any processing. We can use the natural string by adding re.g: # natural string print "hello tan\ nhello tan" print r "hello tan\ nhello tan" output: repetition of the hello tan\ nhello tan string: if you want to repeat the output of a string, you can use the repetition operator of the string For example, if you repeat the output of hi for 7 times, you can use "hi" * 7print "Hello World\ n" * 7 substring: if you want to get a substring out of a string, you need to perform substring operation. There are two main methods of substring operation: 1. Index operation algorithm [] 2. The slicing algorithm [:] # substring # index operator starts at 0 and the slicing operator [aVOB] starts from subscript a to subscript b-1. Similarly, the index S1 = "helloworld" S2 = S1 [0] S3 = S1 [7] S4 = S1 [: 7] S5 = S1 [7:] S6 = S1 [3:7] print s6U3:Python data type basic data type: lists of numbers and strings do not have the concept of arrays in python, and the concepts closest to arrays in python are lists and tuples. A list is a container used to store a series of elements. The list is represented by [], and the elements in the list are arranged in order, starting with element 0. # list drinks= ["Coca-Cola", "Pepsi", "Sprite", "Fanta", "Melinda"] print drinks [1] the elements in the tuple are also the difference between the calculated list and the tuple: 1. The values of the elements in the list can be modified, but the values of the elements in the tuple cannot be modified, and can only be read. The symbol of the list is [], while the symbol of the tuple is () # tuple drinks= ("Coca-Cola", "Pepsi", "Sprite", "Fanta", "Melinda") print drinks [1] # cannot be modified or else the error report drinks [1] = "Lan Fangyuan" print drinks [1] collection python has two main functions, one is to establish relationships. Another function is to eliminate duplicate elements. The format of the collection is: set (element) # collection a=set ("asfddseegsak") b=set ("sfca") # intersection c=a&b print c # union Delima | b print d # subtractive e=a-b print e # remove repeating elements new=set (a) the dictionary in the dictionary python is also called an associative array, enclosed in braces {}. Format: zidian= {'name':'tan','location':'china','like':'sleep'}. The dictionary contains a whole thing, and the whole thing includes all kinds of details. For example, the above contains the specific information of name, location and like. # Dictionary d = {"name": "tan", "country": "China"} print d ["country"] # add the item d ["hobby"] = "sleep" print d ["name"] print d ["hobby"] U4:Python identifier naming rules: 1. The first character of the identifier must be a letter or underscore, and the first character must not have a number or any other character 2. Except for the first character, the identifier can be said to be a letter or an underscore or the number 3. Keywords in case-sensitive python refer to identifiers that come with a specific meaning in the system. The commonly used python keywords are: and elif global or else pass break continue import class return for while printU5:Python object what is the object of python? In python, everything is an object, and the built-in object types mainly include arrays, strings, lists, tuples, dictionaries, collections and so on. Pickle pickling in python if you need to persist some objects without losing their type and data, you need to serialize these objects. After serialization, when you need to use them, we will restore them to the previous data. This process of serialization is called pickle (pickling) # pickle pickling import pickle # dumps (object) serializing the object lista= ["one", "two", "three"] listb=pickle.dumps (lista) print listb # loads (string) to restore the object as it is And the object type is also restored to the original format listc=pickle.loads (listb) print listc # dump (object,file) to serialize group1= ("four", "five", "six") f1=file ("1.pk1", "wb") pickle.dump (group1,f1,True) f1.close () # load (object) File) restore the data stored by dump () in the file f2=file ('1.pk1) t=pickle.load (f2) print t f2.close () U6:Python lines and indents to understand logical lines and physical lines: logical lines mainly refer to the number of lines in the sense of a piece of code Physical line refers to the number of rows actually seen # logical line and physical line # 2 physical lines print "123" print "345" # 1 physical line, 2 logical lines print "123" Print "345" # 1 logical lines, 2 physical lines print''are you all right? are you all right?' 'rules for the use of semicolons in lines: in python, a physical line can generally include multiple logical lines. When writing multiple logical lines in a physical line, the logical lines and logical lines are separated by semicolons. Each logical line must be followed by a semicolon, but if a logical line occupies the end of a physical line, the semicolon can be omitted. Line concatenation: without using triple quotation marks, you can also use line concatenation to grab multiple lines (that is, write a logical line in multiple physical lines) # Line concatenation print'no antidote 'what is indentation? Python has a very different point. In python, the white space at the beginning of the logical line is specified, and the blank space at the beginning of the logical line is incorrect, which will lead to an error message in the execution of the program: how to indent There's an error in your program:unexpected indent by 1. In general, the logical line should not appear at the beginning of the blank 2.if statement indent method 3.while loop indent method # in general, the line should not appear blank import sys # indent there are two ways, one by space Another indentation method of pressing the tab key # if statement axiom 7 if a > 0: print "hi" # while loop indentation method adept 0 while a
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.