Basic syntax of Python notes

Source: Internet
Author: User

1 variables and AssignmentsPython is a dynamic type language and does not require the type of the variable to be declared beforehand. The type of the variable is initialized at the moment of the assignment. The python variable name is case-sensitive, meaning that "case" is a variable that is different from case. Assign ValueAssignment statement: A = 1 A, b =;This comparison has characteristics, can be two together.
2 Numberspython has five basic types of numbers. int (signed integer), long (full), bool (Boolean), float (floating point), complex (plural). It is important to note that Python's long-range is much wider than C, which is limited to the total amount of virtual memory on the user's computer, and in future versions, Python will most likely no longer differentiate between integral and long integers, and unify the two types into long integers. Plural this type is usually not directly supported in other languages, and support for complex numbers is a personalized feature of Python. input
Str=raw_input ("Please input a string:") I=int (raw_input ("Please input a number:")
Different types, slight differences, attention when using.
3 StringThe strings in Python are defined as the character set between quotation marks. Paired single quotes, double quotes, three quotation marks (three consecutive single or double quotes) can be used to represent a string. Where three quotes support multiple lines. The string supports the index operator [] and the slice operator [:]. such as: x= ' ABCDE ', the value of x[0] is ' a ', the value of x[4] is ' e '. In addition, Python supports negative index values, the value of x[-1] is ' e ', it is the last element in the string sequence, the value of x[-2] is ' d ', it is the penultimate element in the string sequence, and if you want to learn more, you can look at the Python list .
several common ways to work with stringsline.split (' a ') #分解字符串, with Javaline.split (' A ', 1)
The Find method is finding the substring at the beginning of the stringstr.find (' a ') #查找, not found return-1
string to lowercase str.lower () uppercase Str.upper ()Judge Lowercase str.islower () uppercase Str.isupper ()
4 Comment "#"The comment statement from Python starts with the "#" sign, until all the content at the end of the line is commented, and the comment code is helpful for collaborative development, so get into this good habit.
5 code block and indent alignmentPython 's code blocks express the code logic by indenting, rather than using curly braces (since this farewell to the sacred curly braces War), Python supports tab indentation and space indentation, but the Python community recommends using four space indents. You can also use tab indentation, but you must not mix the two indentation symbols.
6 Semicolonthe ";" semicolon allows multiple statements to be written on the same line, separated by semicolons, which cannot begin a new block of code on this line. Although this can be done, Python does not advocate the use of ";" to write multiple statements on one line, so that it is not easy to read the code, and it is not convenient to extend and maintain the code later.
7 operatorbecause Python is a strong type of language, so in the case of operators, such as + number, to unify the type of two operands, rather than direct operation, such as an operand is a character type, one is a number, if using the + number, Python will error: TypeError: Unsupported operand type (s) for +: ' int ' and ' str '
8 SELECT statement python advocates a simple and practical idea, it does not have a switch statement, if you want to achieve the effect of a switch statement can be the following two methods (1) through the IF Elif statement to achieveIf condition:...elif conditions:...Else:...
(2) byinfo = {}info = {' A ': ' 1 ', ' B ': 2, ' C ': 3, ' Default ': ' SS '}C = info.get (' A ', ' default ')
9 Cyclesthe commonly used range () function,Range (start, stop) returns a list of integers with a range (num) equivalent to range (0, num)
#普通循环sum =0for i in range (101):     sum+=isum     #5050 #for statement can have else statement for I in Xrange (5):     print Ielse:     print ' Loop is end ' #while语句可以有else语句a = 2while a > 1:     print ' success ' else:     print ' ERROR ' #else部分是可选的. If an else is included, it is always executed once after the For loop ends.

10 Importing Modules
#import语句import sysimport sys.path #from ... import ... Statement from sys import path

11 Functions
def info (x):     # declares a function    return x + 2a = info (1)     # call Print a

Some of the commonly used functions:min (list_name) returns the minimum value of the listMin_index=list_name (min_val) return subscriptlist_name.sort () sort
and so on, there are a lot of, when used to directly check the good.
12 ExceptionsUse of Try/except
values = [-1, 0, 1]for I in range (4): Try:r = 1.0/values[i]print ' reciprocal of ', values[i], ' at ', I, ' is ', rexcept Index Error, E:print ' ERROR: ', eexcept arithmeticerror, e:print ' ERROR: ', E
#执行结果, output exception typereciprocal of-1 at 0 is-1.0Error:float Division by zero
Reciprocal of 1 at 2 is 1.0Error:list Index out of range

Basic syntax of Python notes

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.