The Python Primer series (3)--Python language base syntax

Source: Internet
Author: User
Tags python list in python

This chapter is based primarily on the tutorial simplification of the Python manual (shipped with Python). Have time to view the official original document. You can also find manual when you encounter a module or function that is not clear. Built-in data Types

As with most dynamic languages, a variable in Python is a dynamic variable, so you don't need to specify a variable type when you define it, only when it's actually assigned (all of the variables in Python are objects). numbers (digital)

The use of numbers is the same as mathematical expressions

>>> (50-5*6)/4      # Math expression
5
>>> 7/3             # Default return floor
2
>>> 7/-3
-3
>>> 7/3.0           # floating-point number
2.3333333333333335

Variable Assignment

>>> width =
>>> x = y = Z = ten  # variable can be assigned at the same time
>>> x,y = 100,200   # multiple assignments
>>> print x, y
100 200

In-process conversion

>>> a=100
>>> Hex (a)          # hexadecimal
' 0x64 '
>>> Oct (a)          # octal
' 0144 '

ASCII code Conversion

>>> Ord (' a ') # letter-Turn value ("a")
>>> chr (#) value to the         letter
' a '
String (Strings)

Python represents a string that is caused by single quotes, double quotes, or triple quotes. Here, using single quotes and double quotes are exactly the same, using single quotes as references, strings can be double quotation marks, use double quotes, strings can contain single quotes, or you need to add escape characters

>>> ' doesn\ ' t '
"doesn ' t"
>>> "doesn ' t"
"doesn ' t"
>>> "Yes," he said. "
"Yes," he said.
>>> "yes,\" he said ""
" Yes, "he said.
" >>> ' "isn\ ' t," she said. "
Isn\ ' t, "she said."

Cross-row references, you need and use the \ n and \ Connection characters

>>> print "usage:thingy [options]\n\-
     H                        Display this Usage message\n\-
     h hostname               Hostname to connect to "
usage:thingy [OPTIONS]-
     h Display This Usage message-
     h Hostname               Hostname to connect to

Using triple quotes, "" or "", you can more easily cross line strings

>>> print "" "
usage:thingy [OPTIONS]-
     h Display This Usage message-
     h hostname               hostname To connect to "" "
 usage:thingy [OPTIONS]-
     h Display This Usage message-
     h hostname               hostname To connect to

The original string, which indicates that the string is a raw string and does not escape the characters in it by adding the letter R in front of it

>>> print R "" "AAAAAAAA\NBBBB" "
aaaaaaaa\nbbbb

The string can be connected by the + number, repeated by the * number

>>> word = ' help ' + ' A '
>>> word
' helpa '
>>> ' < ' + word*5 + ' > '
; Helpahelpahelpahelpahelpa> '

The string is indexed in the same way as C, and the subscript starts with 0. At the same time, the substring can use the notation of the fragment, the left of the colon is the subscript of the start character, and the right is the ending character Poute +1

>>> word[4] '
A '
>>> word[0:2]
' he '
>>> Word[2:4]
' LP '

The fragment notation also uses two convenient default values, the left defaults to 0, the right defaults to the entire string length

>>> Word[:2]    # The two characters
' he '
>>> word[2:]    # Everything except the Two characters
' LpA '

Piecewise notation, you can also use a negative subscript to indicate

>>> Word[-1]     # The last character
' A '
>>> word[-2]     # the Last-but-one character
' P '
>>> word[-2:]    # The last two characters
' PA '
>>> word[:-2]    # Everything except the last two characters
' Hel '

When a substring is fetched, it is automatically intercepted if the range is exceeded

>>> word[-100:200]
' Helpa '

Strings can also intercept characters in a step-by-step manner. Such as:

>>> Word[::2]
' HlA

>>> word[::-1]   # reverse output
' Apleh '

The above mainly introduces the interception and concatenation of strings, and other common operations of strings are as follows: Go to the left and right blank characters or special characters

>>> "  aaaa   ". Strip ()          # go to left and right blank character
aaaa
>>> "  aaaa   ". Rstrip ()         Lstrip to the left space, Rstrip to the right space
  aaaa   
>>> "  aaaa,,,...". Rstrip (',.! ') # to specify the character   
'  aaaa '
Take string length
>>> len (word)
5
To locate a character or substring
>>> "AAABBBCCC". Index (' BB ')
3
>>> "AAABBBCCC". Index (' BC ')
5
Comparing strings
>>> cmp (' AA ', ' BB ')
-1
>>> cmp (' AA ', ' AA ')
0
>>> cmp (' BB ', ' AA ')
1
String Capitalization conversions
>>> ' AAA '. Upper () '
aaa '
>>> ' aaaa '. Lower ()
' AAAA '
String Lookup
>>> ' AAABBBCCC '. Find (' BBB ')
3

Index if not found will throw an exception, find not found return-1 string replacement

>>> "AAABBBAAADDDD". Replace (' A ', ' e ')
' eeebbbeeedddd '
>>> ' aaabbbaaadddd '. Replace (' AAA ' , ' e ')
' ebbbedddd '
String segmentation
>>> "AAAAA;; BBB;; ccc;ddd; ". Split (';; ')
[' AAAAA ', ' BBB ', ' ccc;ddd; ']            # string array
>>> ' aaaaa;bbb;ccc;ddd; '. Split (';')
[' AAAAA ', ' BBB ', ' CCC ', ' ddd ', ']
Merging strings
>>> '. Join ([' AAAA ', ' BBB ', ' CCC '])
' AAAABBBCCC '
>>> '; Join ([' AAAA ', ' BBB ', ' CCC '])
' AAAA;BBB;CCC '

Python strings are not modifiable. If you modify a character, you should use replace, or use the left string + new character + right string concatenation to list (array)

Python uses the following syntax to define LIST,LIST element types can be different

>>> a = [' spam ', ' eggs ', 1234]
>>> a
[' spam ', ' eggs ', 100, 1234]

The fragment notation for list access is similar to string, and the same uses + to connect, * repeat

>>> a[1:-1]
[' eggs ', MB]
>>> a[:2] + [' bacon ', 2*2]
[' spam ', ' eggs ', ' bacon ', 4]
>>> 3*a[:3] + [' boo! ']
[' spam ', ' eggs ', m, ' spam ', ' eggs ', ' spam ', ' eggs ', M, ' boo! ']

Unlike strings, the Python list can be modified

>>> letters = [' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' G ']
>>> # Replace some values
>>> letters [2:5] = [' C ', ' d ', ' e ']
>>> letters
[' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' G ']
>>> # now remove the M
>>> Letters[2:5] = []
>>> letters
[' A ', ' B ', ' F ', ' G ']

return list size

>>> a = [' A ', ' B ', ' C ', ' d ']
>>> len (a)
4

List can be nested to construct multidimensional arrays

>>> p=[' A ', ' B ']
>>> p2=[' A ', p, ' B ']
>>> p2
[' A], [' A ', ' B '], ' B ']

List other common operations: Append (x) add an element to the end extend (x) equivalent + insert (x) remove x pop () eject index (x) to return the first matching X's subscript count (x) return the horse With x number sort (Cmp=none, Key=none, Reverse=false) sorted reverse () Generate inverse ordinal group

Note that the difference between append and +, append an array, is to add an array as an element, + the array is to add all the elements

List also provides a method called list comprehensions that can generate a new list from a list, referencing the idea of filter-map-reduce in functional programming [refer to Chapter 5th]

>>> l=range                 
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> [x**2 for X in L if x%2]
  # returns the odd squared in the list
[1, 9, 25, 49, 81]
tuple (meta Group)

The tuple is composed of multiple values and commas, preceded by parentheses, and can be added without

>>> t = 12345, 54321, ' hello! '
>>> t[0]
12345
>>> t
(12345, 54321, ' hello! ')
>>> (A,b) = (2, 3)
>>> c,d = 1, (2, 3)
>>> len (d)
2

Unlike the list, tuple is not modifiable, so the data in tuple cannot be modified. Tuple are typically used when assigning, printing, or pack,unpack. Examples of tuple printing

>>> print "Hello,%s,%s,%s"% (' 1 ', ' 2 ', ' 3 ')  #此时tuple需要加 () Otherwise syntax error
Set (set)

Set is unordered, the element does not duplicate the collection. Used primarily for member detection and elimination of duplicate elements. Collections can be generated by curly braces, arrays, and strings. The collection also supports operations such as a set, intersection, difference set, and so on

>>> A={1, 2, 2, 2, 3}
>>> a
set ([1, 2, 3])
>>> Set ([' 1 ', ' 2 ', ' 2 ', ' 3 '])
set ([' 1 ', ' 3 ', ' 2 '])
>>> ' orange ' in fruit                 # Fast Membership testing
True
  >>> # demonstrate S ET operations on the unique letters from two words
...
>>> a = set (' Abracadabra ')
>>> b = Set (' Alacazam ')
>>> a                                  # unique letters in a< C13/>set ([' A ', ' R ', ' B ', ' C ', ' d '])
>>> a-b                              # Letters in a but not in B
set ([' R ', ' d ', ' B ']) 
  >>> A | b                              # Letters in either A or B
set ([' A ', ' C ', ' R ', ' d ', ' B ', ' m ', ' Z ', ' l '])
>>> A & B                              # le Tters in both A and B
set ([' A ', ' C '])
>>> a ^ b                              # Letters in a or B but not both
set ([' R ', ' D ', ' B ', ' m ', ' Z ', ' l ']
Dictionary (dictionary)

Dictionary is unordered, set of key-value pairs

>>> Tel = {' Jack ': 4098, ' Sape ': 4139}
>>> tel[' guido '] = 4127
>>> Tel
{' Sape ': 41 The ' Guido ': 4127, ' Jack ': 4098}
>>> tel[' Jack ']
4098
>>> del tel[' Sape ']             
>> > tel[' irv '] = 4127
>>> Tel
{' Guido ': 4127, ' Irv ': 4127, ' Jack ': 4098}
>>> Tel.keys () C10/>[' Guido ', ' Irv ', ' Jack ']
>>> ' Guido ' in Tel
True
 >>> dict ([(' Sape ', 4139), (' Guido ', 4127, (' Jack ', 4098)]
{' Sape ': 4139, ' Jack ': 4098, ' Guido ': 4127}

If the key is a simple string, dict can also construct this

>>> dict (sape=4139, guido=4127, jack=4098)
{' Sape ': 4139, ' Jack ': 4098, ' Guido ': 4127}

The Del operation can be used in a variable structure such as list, set, dictionary, and so on to remove other types of elements

Other types also have None null value True Boolean type false Boolean type Deque queue, requires import collections nametuple named tuple expression

The expression in Python has the following characteristics: The statement does not need to; At the end, different statements require a newline syntax block (if,while,for,defun,class, etc.) instead of using the parentheses to determine the scope, instead, the code is aligned to determine that Python makes the code more readable by means of a syntax-enforced alignment, as an example of the following if code block

>>> # Plus: block multiple statements are aligned with TAB or space
>>> if 1>2:
    print ' 1 '
    print ' 2 '
 >>> # No alignment causes syntax errors
>>> if 1>2:
    print ' 1 '
      print ' 2 ' File ' <pyshell#38> ', line

  3
    print ' 2 '
    ^
indentationerror:unexpected Indent
Comment Empty statement pass with # number Control Flow Conditional Judgment

The conditional judgment grammar is very simple, if...elif...else, as follows

>>> x = Int (raw_input ("Please enter a integer:") Please
enter a integer:42
 >>> if x < 0:
    print ' Negative '
elif x = = 0:
    print ' Zero '
else:
    print ' Positive '
 Positive

In addition to the comparison, you can also be a number of operations. In and not to determine whether elements are in a sequence (list,tuple,set,string,dictionary, etc.), and is and not are used to determine whether an element is the same object

>>> ' 1 ' in [' 1 ', ' 2 ', ' 3 ']
true
>>> ' 1 ' in (' 1 ', ' 2 ', ' 3 ')
true
>>> ' 1 ' in {' 1 ', ' 2 ', ' 3 '}
true
>>> ' 1 ' in {' 1 ': 1, ' 2 ': 1}
True

The judgment on the object that returns True if the object is not of type none

>>> if not None:
    print "It" s true "

it" s true

Compound conditions have not, and, or, not has the highest precedence, or has the lowest precedence, and and or is evaluated in a regular order, that is, the condition is judged from left to right, a conditional expression is evaluated when there is a need to judge, and when a condition is false, Or when a condition is true, the subsequent conditional judgment does not go on. The return value of and OR or is the last evaluated conditional expression value

>>> string1, string2, string3 = ', ' Trondheim ', ' Hammer dance '
>>> non_null = string1 or string2 or String3
>>> print non_null
Trondheim

Unlike the C language, Python cannot assign values in conditional judgments. This avoids the = = and = Easy to write wrong iterations

Use a while for iterations, continue, break, and so on, similar to C

I=0 while
i<3:
    if i%2:
        
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.