In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
In this issue, the editor will bring you the grammar and types that you need to know about the introduction to Python. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.
One of the design goals of Python is to make the source code highly readable. It is designed to use punctuation and English words that are often used in other languages to make the source code look neat and beautiful as a whole. It does not need to rewrite declaration statements like static languages such as C and Pascal, nor does it often have special situations and surprises like their syntax.
Indent
Python developers deliberately force programmers to develop good programming habits by preventing programs that violate indentation rules from being compiled. And in Python, indentation, rather than curly braces or certain keywords, is used to indicate the beginning and exit of a statement block. Increasing indentation indicates the beginning of a statement block, while decreasing indentation indicates the exit of a statement block. Indentation becomes part of the grammar. For example
If statement:
If age
< 21: print("你不能買酒。") print("不過你能買口香糖。") print("這句話處於if語句塊的外面。") 根据PEP的规定,必须使用4个空格来表示每级缩进。使用Tab字符和其它数目的空格虽然都可以编译通过,但不符合编码规范。支持Tab字符和其它数目的空格仅仅是为了兼容很旧的Python程序和某些有问题的编辑器。 语句和控制流 ◆ if语句,当条件成立时执行语句块。经常与else,elif(相当于else if)配合使用。 ◆ for语句,遍历列表、字符串、字典、集合等迭代器,依次处理迭代器中的每个元素。 ◆ while语句,当条件为真时,循环执行语句块。 ◆ try语句。与except,finally配合使用处理在程序运行中出现的异常情况。 ◆ class语句。用于定义类型。 ◆ def语句。用于定义函数和类型的方法。 ◆ pass语句。表示此行为空,不执行任何操作。 ◆ assert语句。用于程序调试阶段时测试运行条件是否满足。 ◆ with语句。Python2.6以后定义的语法,在一个场景中运行语句块。比如,运行语句块前加锁,然后在语句块运行结束后释放它。 ◆ yield语句。在迭代器函数内使用,用于返回一个元素。自从Python 2.5版本以后。这个语句变成一个运算符。 表达式 Python的表达式写法与C/C++类似。只是在某些写法有所差别。 ◆ 主要的算术运算符与C/C++类似。+, -, *, /, //, **, ~, %分别表示加法或者取正、减法或者取负、乘法、除法、整除、乘方、取补、取模。>>, > sum (x * x for x in range (10))
◆ Python uses lambda to represent anonymous functions. The anonymous function body can only be an expression. For example:
> add=lambda x, y: X + y > add (3penny 2) 5
◆ Python uses y if cond else x to represent conditional expressions. It means that when cond is true, the value of the expression is y, otherwise it is x. The equivalent of cond?y:x in C++ and Java.
There are two types of ◆ Python: distinguishing lists (list) and tuples (tuple). The way list is written is [1magin 2pr 3], while the way tuple is written is (1pm 2p3). You can change the elements in the list, not the tuple. In some cases, the parentheses of tuple can be omitted. Tuple has special handling for assignment statements. Therefore, you can assign values to multiple variables at the same time, such as:
> XBI y = 1,2 # assign values to XBI y at the same time, and the final result: Xray 1, YQ 2.
In particular, ◆ can use the following form to exchange the values of two variables:
> x, yellowy, x # final result: yellow1, xroom2
◆ Python uses'(single quotation marks) and "(double quotation marks) to represent strings. Unlike Perl, Unix Shell, or Ruby, Groovy and other languages, the two symbols serve the same purpose. In general, if double quotes appear in a string, single quotation marks are used to represent the string; otherwise, double quotation marks are used. If none of them show up, choose according to your personal preference. The\ (backslash) that appears in the string is interpreted as a special character, such as\ n represents a newline character. The r before the expression indicates that Python does not interpret the\ that appears in the string. This type of writing is often used to write regular expressions or Windows file paths.
◆ Python supports list cutting (list slices), which allows you to get part of the complete list. The types that support cutting operations are str, bytes, list, tuple and so on. Its syntax is... [left:right] or... [left:right:stride]. Assuming that the value of the nums variable is [1, 3, 5, 7, 8, 13, 20], the following statements are true:
◆ nums [2:5] = = [5,7,8] cuts from elements with subscript 2 to elements with subscript 5, but does not include elements with subscript 2.
◆ nums [1:] = [3, 5, 7, 8, 13, 20] cut to an element.
◆ nums [:-3] = = [1, 3, 5, 7] cuts from the initial element to the penultimate element.
◆ nums [:] = = [1, 3, 5, 7, 8, 13, 20] returns all elements. Changing the new list will not affect nums.
◆ nums [1:5:2] = [3,7]
Function
Python's functions support recursion, default parameter values, and variable parameters, but do not support function overloading. In order to enhance the readability of the code, you can write "Documentation Strings" (or docstrings for short) after the function to explain the function of the function, the type and meaning of the parameter, the type and range of the return value, and so on. You can use the built-in function help () to print out the help for using the function. For example:
Def randint (a, b):... "Return random integer in range [a, b], including both end points." > > help (randint) Help on function randint in module _ main__: randint (a, b) Return random integer in range [a, b], including both end points.
Method of object
The method of an object is a function that is bound to an object. The syntax for calling object methods is instance.method (arguments). It is equivalent to calling Class.method (instance, arguments). When defining an object method, you must explicitly define * parameters as self to access the object's internal data. Self is equivalent to the this variable in Java. For example:
Class Fish: def eat (self, food): if food is not None: self.hungry=False # an example of constructing Fish: f=Fish () # the following two call forms are equivalent: Fish.eat (f, "earthworm") f.eat ("earthworm")
Python knows some special method names that start with "_" and end with "_" that are used to implement operator overloading and a variety of special functions.
Types
Python adopts dynamic type system. At compile time, Python does not check whether the object has the called method or property, but does not check until run time. So an exception may be thrown when manipulating an object. However, although Python uses a dynamic type system, it is also strongly typed. Python forbids operations that are not clearly defined, such as adding strings to numbers.
Like other object-oriented languages, Python allows programmers to define types. To construct an object, you only need to call the type like a function, for example, for the previously defined Fish type, use Fish (). The type itself is an object of the special type type (the type type itself is also a type object), and this special design allows reflection programming of the type.
Python has a rich set of data types built in. Compared with Java and C++, these data types effectively reduce the length of code. The following list briefly describes the Python built-in data types (for Python 3.x):
In addition to various data types, the Python language also uses types to represent functions, modules, types themselves, methods of objects, compiled Python code, runtime information, and so on. Therefore, Python is very dynamic.
Mathematical operation
Python uses operators similar to C and Java to support the mathematical operations of integers and floating-point numbers. At the same time, it also supports complex operations and integer operations of infinite digits (actually limited by the ability of the computer). Except for the absolute value function abs (), most mathematical functions are in the math and cmath modules. The former is used for real operations, while the latter is used for complex operations. You need to import them first when using them, such as:
> import math > print (math.sin (math.pi/2)) 1.0
The fractions module is used to support fractional operations, and the decimal module is used to support high-precision floating-point operations.
Python defines that the value of the remainder operation a% b is in the open interval [0, b]. If b is negative, the open interval becomes (b, 0]. This is a very common way of definition. But it actually depends on the definition of divisible. In order to make the equation: B * (a / b) + a% b = a true, divisible operation needs to take a value in the direction of negative infinitesimal. For example, the result of 7 / 3 is 2, while the result of (- 7) / 3 is-3. This algorithm is different from many other programming languages, it should be noted that their division operation will take a value in the direction of 0.
Python allows you to write two comparison operators in conjunction with each other, as is commonly used in mathematics. For example, a < b < c is equivalent to a < b and b < c. C++ 's result is different from Python in that it first calculates a < b, gets one of 0 or 1 values based on the size of the two, and then compares it with c.
These are the grammars and types that the editor needs to know about the introduction to Python. If you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.
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.