This article is participating in Python Theme Month. See the link to the event for more details
HXDM, HJMM, I am an unwomanly cat.
This article is a quick introduction to Python at the front end. It is the minimum required to get you started on Pthon. Too much is not a good introduction.
The environment
For beginners, the biggest hurdle is the environment
linux
Built-in 2.7 x
Python -v python 2.7.5Copy the code
Here to download Python – 3.6.1. TGZ, see the reader need version: www.python.org/downloads/s…
Tar -zxvf python-3.6.1. TGZ CD python-3.6.1./configure make && make installCopy the code
Test the version
Python3 -v Python 3.6.1Copy the code
win
Download address www.python.org/downloads/w… 2. X and 3. X are installed in different directories, so you can change python.exe to python3.exe or python2.exe. Just remember to add the environment variable.
mac
Built-in 2.7 x
Python -v python 2.7.16Copy the code
Brew install [email protected]. When installing Tk, you will install the corresponding Python version, which is python3.9. You can change it if you want
Python 3.9.6 python3 - VCopy the code
Refer to another article on environment issues in this article, which addresses all problems with switching versions of Python
start
Chinese code
# -* -coding: utf-8 -*- utf-8 -*-
#! /usr/bin/python # -* -coding: utf-8 -* -print (" Hello world ")Copy the code
RPEL Interactive interpreter
Python Python 3.7.5 (default, Jul 9 2021, 09:40:22) [Clang 11.0.3 (clang-1103.0.32.62)] on Darwin Type "help", "Copyright ", "credits" or "license" for more information. >>> print(' I'm a pussy '); I'm an unwomanly cat >>>Copy the code
Execute permission (If the execution cannot be performed, you need to add execute permission)
Chmod +x test.py # Add executable permission to the script file./test.pyCopy the code
Python2.x is compatible with 3.x
# python 2 x > > > list = [" a ", "b", "c"]] > > > print the list [' a ', 'b', 'c'] # disable print the list, Print () >>> from __future__ import print_function # Print list File "<stdin>" Line 1 print list ^ SyntaxError: invalid syntax >>> print (list)Copy the code
Note: Many of the features designed for python3.x compatibility with Python2.x can be imported through the future package.
version
Python -v # 方法2 import platform print(platform.python_version()) 3.7.3 Print (sys.version_info) 3.7.3 (default, Jun 2 2020, [Clang 11.0.3 (clang-1103.0.32.62)] sys.version_info(major=3, minor=7, micro=3, releaselevel='final', serial=0)Copy the code
Python Execution Script
Which python or which python3, check the location of Python and change the following #! /usr/bin/python
#! /usr/bin/pythonprint ("Hello, Python!" )Copy the code
identifier
The name contains letters, digits, and underscores (_). It is case sensitive and cannot start with a digit. An __foo starting with a single underscore represents a class attribute that is not directly accessible, an __foo beginning with a double underscore represents a private member of the class, and an __foo__ beginning and ending with a double underscore represents an identity that is unique to special methods in Python, such as __init__() for a class’s constructor.
Reserved words
Reserved words, lowercase letters only, do not use
bao | leave | word |
---|---|---|
and | exec | not |
assert | finally | or |
break | for | pass |
class | from | |
continue | global | raise |
def | if | return |
del | import | try |
elif | in | while |
else | is | with |
except | lambda | yield |
Line and indent
Python code blocks do not use curly braces {} to control classes, functions, and other logical decisions. Use indentation instead. The amount of indented space is variable, but all block statements must contain the same amount of indented space. This must be strictly enforced.
if True:
print ("True")
else:
print ("False")
Copy the code
Multi-line statement
total = item_one + \
item_two + \
item_three
Copy the code
Statements containing [], {}, or () parentheses do not require multi-line hyphens
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
Copy the code
quotes
Word = 'word' sentence = "This is a sentence." Paragraph = "" this is a paragraph. Contains multiple statements """Copy the code
annotation
Print ("Hello, Python!") This is a multi-line comment, using single quotes. This is a multi-line comment, using single quotes. This is a multi-line comment, using single quotes. """ "This is a multi-line comment, using double quotes. This is a multi-line comment, with double quotes. This is a multi-line comment, with double quotes. "" "Copy the code
A blank line
Blank lines make your code more readable and do nothing else.
Waiting for user input
Raw_input (" Press Enter to exit, any other key displays... \n")Copy the code
\ n line
Multiple statements on the same line
; separated
#! /usr/bin/python import sys; x = 'huamiao'; sys.stdout.write(x + '\n')Copy the code
Print uses a newline by default. If you want to do this, put a comma at the end of the variable.
#! /usr/bin/python # -*- coding: Utf-8 -* -x ="a" y="b" utF-8 -* -x ="a" y="b" utF-8 -* -x ="a" y="bCopy the code
Multiple statements form a code group
Compound statements such as if, while, def, and class begin with a keyword and end with a colon:
if expression :
suite
elif expression :
suite
else :
suite
Copy the code
Command line arguments
python -h
usage: /usr/local/bin/python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b : issue warnings about str(bytes_instance), str(bytearray_instance)
and comparing bytes/bytearray with str. (-bb: issue errors)
-B : don't write .pyc files on import; also PYTHONDONTWRITEBYTECODE=x
-c cmd : program passed in as string (terminates option list)
-d : turn on parser debugging output (for experts only, only works on
debug builds); also PYTHONDEBUG=x
-E : ignore PYTHON* environment variables (such as PYTHONPATH)
-h : print this help message and exit (also --help)
-i : inspect interactively after running script; forces a prompt even
if stdin does not appear to be a terminal; also PYTHONINSPECT=x
-I : isolate Python from the user's environment (implies -E and -s)
-m mod : run library module as a script (terminates option list)
-O : remove assert and __debug__-dependent statements; add .opt-1 before
.pyc extension; also PYTHONOPTIMIZE=x
-OO : do -O changes and also discard docstrings; add .opt-2 before
.pyc extension
-q : don't print version and copyright messages on interactive startup
-s : don't add user site directory to sys.path; also PYTHONNOUSERSITE
-S : don't imply 'import site' on initialization
-u : force the stdout and stderr streams to be unbuffered;
this option has no effect on stdin; also PYTHONUNBUFFERED=x
-v : verbose (trace import statements); also PYTHONVERBOSE=x
can be supplied multiple times to increase verbosity
-V : print the Python version number and exit (also --version)
when given twice, print more information about the build
-W arg : warning control; arg is action:message:category:module:lineno
also PYTHONWARNINGS=arg
-x : skip first line of source, allowing use of non-Unix forms of #!cmd
-X opt : set implementation-specific option. The following options are available:
-X faulthandler: enable faulthandler
-X oldparser: enable the traditional LL(1) parser; also PYTHONOLDPARSER
-X showrefcount: output the total reference count and number of used
memory blocks when the program finishes or after each statement in the
interactive interpreter. This only works on debug builds
-X tracemalloc: start tracing Python memory allocations using the
tracemalloc module. By default, only the most recent frame is stored in a
traceback of a trace. Use -X tracemalloc=NFRAME to start tracing with a
traceback limit of NFRAME frames
-X importtime: show how long each import takes. It shows module name,
cumulative time (including nested imports) and self time (excluding
nested imports). Note that its output may be broken in multi-threaded
application. Typical usage is python3 -X importtime -c 'import asyncio'
-X dev: enable CPython's "development mode", introducing additional runtime
checks which are too expensive to be enabled by default. Effect of the
developer mode:
* Add default warning filter, as -W default
* Install debug hooks on memory allocators: see the PyMem_SetupDebugHooks() C function
* Enable the faulthandler module to dump the Python traceback on a crash
* Enable asyncio debug mode
* Set the dev_mode attribute of sys.flags to True
* io.IOBase destructor logs close() exceptions
-X utf8: enable UTF-8 mode for operating system interfaces, overriding the default
locale-aware mode. -X utf8=0 explicitly disables UTF-8 mode (even when it would
otherwise activate automatically)
-X pycache_prefix=PATH: enable writing .pyc files to a parallel tree rooted at the
given directory instead of to the code tree
--check-hash-based-pycs always|default|never:
control how Python invalidates hash-based .pyc files
file : program read from script file
- : program read from stdin (default; interactive mode if a tty)
arg ...: arguments passed to program in sys.argv[1:]
Other environment variables:
PYTHONSTARTUP: file executed on interactive startup (no default)
PYTHONPATH : ':'-separated list of directories prefixed to the
default module search path. The result is sys.path.
PYTHONHOME : alternate <prefix> directory (or <prefix>:<exec_prefix>).
The default module search path uses <prefix>/lib/pythonX.X.
PYTHONPLATLIBDIR : override sys.platlibdir.
PYTHONCASEOK : ignore case in 'import' statements (Windows).
PYTHONUTF8: if set to 1, enable the UTF-8 mode.
PYTHONIOENCODING: Encoding[:errors] used for stdin/stdout/stderr.
PYTHONFAULTHANDLER: dump the Python traceback on fatal errors.
PYTHONHASHSEED: if this variable is set to 'random', a random value is used
to seed the hashes of str and bytes objects. It can also be set to an
integer in the range [0,4294967295] to get hash values with a
predictable seed.
PYTHONMALLOC: set the Python memory allocators and/or install debug hooks
on Python memory allocators. Use PYTHONMALLOC=debug to install debug
hooks.
PYTHONCOERCECLOCALE: if this variable is set to 0, it disables the locale
coercion behavior. Use PYTHONCOERCECLOCALE=warn to request display of
locale coercion and locale compatibility warnings on stderr.
PYTHONBREAKPOINT: if this variable is set to 0, it disables the default
debugger. It can be set to the callable of your debugger of choice.
PYTHONDEVMODE: enable the development mode.
PYTHONPYCACHEPREFIX: root directory for bytecode cache (pyc) files.
Copy the code
variable
Variable assignment
#! /usr/bin/python # -*- coding: Utf-8 -* -counter = 100 # Assign integer variable miles = 1000.0 # float name = "John" # string print counter print Miles print nameCopy the code
Multiple variable assignments
a = b = c = 1
a, b, c = 1, 2, "john"
Copy the code
Standard data type
- Numbers
- String (String)
- List (List)
- Tuple (Tuple)
- A Dictionary is a Dictionary.
digital
Python supports four different number types:
- Int (signed integer)
- Long (long integer [can also represent octal and hexadecimal])
- Float (floating point)
- For complex numbers
int | long | float | complex |
---|---|---|---|
10 | 51924361L | 0.0 | 3.14 j. |
100 | -0x19323L | 15.20 | 45.j |
– 786. | 0122L | 21.9 | 9.322 e-36 j |
080 | 0xDEFABCECBDAECBFBAEl | 32.3 e+18 | .876j |
– 0490. | 535633629843L | – 90. | -.6545+0J |
-0x260 | -052318172735L | 32.54 e100 | 3e+26J |
0x69 | -4721885298529L | 70.2 e-12 | 4.53 e-7 j |
- You can also use lowercase L for long integers, but it is recommended that you use uppercase L to avoid confusion with the number 1. Python uses L to display long integers.
- Python also supports complex numbers, which consist of a real part and an imaginary part and can be represented as a + bj, or complex(a,b). Both the real part a and the imaginary part B of a complex number are floating point.
Note: Long only exists in python2.x. In versions after 2.2, int overflow is automatically converted to long. In python3. X the long type is removed and replaced with int.
To delete a variable
You can remove references to one or more objects by using the DEL statement. Such as:
del var
del var_a, var_b
Copy the code
string
#! /usr/bin/python # -*- coding: UTF-8 -*- str = 'Hello World! 'print STR # print output complete string STR [0] # the first character in the output string print STR [but] # in the output string between the third and sixth print string STR [2:] # output from the third character string Print STR * 2 # print STR + "TEST" # print stringCopy the code
The list of
The most frequently used data type in Python.
#! /usr/bin/python # -*- coding: Utf-8 -* -list = ['huamiao', 786, 2.23, 'John ', 70.2] tinylist = [123, utF-8 -* -list = ['huamiao', 786, 2.23,' John ', 70.2] Print list[0] # print list[1:3] # print list[2:] # Print list[1:] # print list[1: Print tinylist * 2 # print tinylist * 2 # print tinylistCopy the code
tuples
A read-only list
#! /usr/bin/python # -*- coding: Utf-8 -* -tuple = ('huamiao', 786, 2.23, 'John ', 70.2) tinytuple = (123, 'huamiao', 786, 2.23,' John ', 70.2) Print tuple[0] # Print tuple[1:3] # Print tuple[2:] # print tuple[2:] # Print tinytuple * 2 # Print tuple + tinytuple # Print tuple + tinytuple # Print tupleCopy the code
The dictionary
Js like object
#! /usr/bin/python # -*- coding: UTF-8 -*- dict = {} dict['one'] = "This is one" dict[2] = "This is two" tinydict = {'name': 'huamiao','code':6734, 'dept': 'sales'} print dict['one'] # print tinydict [2] # print tinydict # print tinydict.keys() # Print tinydict.values() # Print all valuesCopy the code
Data type conversion
function | describe |
---|---|
int(x [,base]) | Convert x to an integer |
long(x [,base] ) | Converts x to a long integer |
float(x) | Convert x to a floating point number |
complex(real [,imag]) | Create a complex number |
str(x) | Converts object X to a string |
repr(x) | Converts object X to an expression string |
eval(str) | Used to evaluate a valid Python expression in a string and return an object |
tuple(s) | Converts the sequence S to a tuple |
list(s) | Converts the sequence S to a list |
set(s) | Convert to a mutable set |
dict(d) | Create a dictionary. D must be a sequence (key,value) tuple. |
frozenset(s) | To an immutable set |
chr(x) | Converts an integer to a character |
unichr(x) | Converts an integer to a Unicode character |
ord(x) | Converts a character to its integer value |
hex(x) | Converts an integer to a hexadecimal string |
oct(x) | Converts an integer to an octal string |
The operator
Arithmetic operator
The operator | describe | The instance |
---|---|---|
+ | Add – Add two objects | A + B outputs 30 |
– | Minus – you get a negative number or one number minus another number | A-b The output is -10 |
* | Multiply – multiply two numbers or return a string that has been repeated several times | A * b outputs 200 |
/ | Over minus x over y | B/A Output 2 |
% | Take modulo – Returns the remainder of a division | B % a Output 0 |
支那 | Power – Returns x to the y power | A **b is 10 to the 20th power, and the output is 100000000000000000000 |
// | Divisible – Returns the integer part of the quotient (Take down the whole9 / / 2 = > 4 |
#! /usr/bin/python # -*- coding: Utf-8 -* -a = 21 b = 10 c = 0 c = a + b print "1 -c = a -b print "2 -c = a -b print" ", c c = a * b print ", c c = a/b print ", c c = a/b print ", c c = a % b print ", c c = a % b print ", c c = a % b print ", c c = a % b print" A = 2 b = 3 c = a**b print "6 -c = ", c a = 10 b = 5 c = a//b print "7 -c = ", c #Copy the code
Note: in PYTHon2.x, dividing an integer by an integer yields only an integer. If you want the decimal part, just change one of the numbers to a floating point.
>>> 1/2 0 >> 1.0/2 0.5 >>> 1/float(2) 0.5Copy the code
Comparison operator
The following assumes that variable A is 10 and variable B is 20:
The operator | describe | The instance |
---|---|---|
= = | Equals – Compares objects for equality | A == b returns False. |
! = | Not equal – Compares two objects to see if they are not equal | (a ! = b) returns true. |
<> | Not equal – Compares two objects to see if they are not equal. Python3 is deprecated. | (a <> b) returns true. This operator is similar! =. |
> | Greater than – Returns whether x is greater than y | (a > b) return False. |
< | Less than – Returns whether x is less than y. All comparison operators return 1 for true and 0 for false. This is equivalent to the special variables True and False, respectively. | (a < b) returns true. |
> = | Greater than or equal to – Returns whether x is greater than or equal to y. | Return False (a >= b) |
< = | Less than or equal to – Returns whether x is less than or equal to y. | (a <= b) returns true. |
#! /usr/bin/python # -* -coding: utf-8 -* -a = 21 b = 10 c = 0 if a == b: print "1 - a = b" else: Print "1 - a does not equal b" if a! = b: print "2 - a = b" else: print "2 - a = b" if a <> b: print "3 - a = b" else: print "3 - a = b" if a <> b: print "3 - a = b" else: print "3 - a = b" if a <> b: print "3 - a = b" else: print "3 - a = b" if a <> b: print "3 - a = b" Print "4 -a > b" else: print "4 -a > b" if a > b: print "5 -a > b" else: print "4 -a > b" if a > b: print "5 -a > b" else: If a <= b: print "6-a <= b" else: print" 6-a <= b" if b >= a: print "6-a <= b" else: print" 6-a <= b" if b >= a: print "6-a <= b" Print "7 -b < a" else: print "7 -b < a"Copy the code
Assignment operator
The following assumes that variable A is 10 and variable B is 20:
The operator | describe | The instance |
---|---|---|
= | Simple assignment operator | C = a + b assigns the result of the operation a + b to c |
+ = | The addition assignment operator | C += a is the same thing as c = c + A |
– = | Subtraction assignment operator | C minus a is the same thing as c equals c minus a |
* = | The multiplication assignment operator | C times a is the same thing as c equals c times a |
/ = | Division assignment operator | C/a is the same thing as c = c/a |
% = | The modulo assignment operator | C %= a is equivalent to C = C % a |
* * = | Power assignment operator | C **= a is equivalent to c = c ** a |
/ / = | Take the divisor assignment operator | C //= a is equivalent to c = c // a |
#! /usr/bin/python # -*- coding: Utf-8 -* -a = 21 b = 10 c = 0 c = a + b print "1 -c = "c c += a print "2 -c =" c c *= a print "3 -c = ", c c /= a print ", c c = 2 c %= a print ", c c **= a print ", c c = 2 c %= a print ", c c **= a print" ", c c //= a print "7 -c = ", cCopy the code
An operator
Bitwise operators compute numbers as if they were binary. The bitwise algorithm in Python is as follows:
In the following table, a is 60, b is 13, and the binary format is as follows:
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
Copy the code
The operator | describe | The instance |
---|---|---|
& | Bitwise and operator: The two values involved in the operation, the result of which is 1 if both corresponding bits are 1, and 0 otherwise | (a & b) output 12, binary interpretation: 0000 1100 |
Bitwise or operator: as long as one of the corresponding two binary bits is 1, the resulting bit is 1. | ||
^ | Bitwise Xor operator: when two corresponding binaries are different, the result is 1 | (a ^ b) Output 49, binary interpretation: 0011 0001 |
~ | Bitwise invert operator: inverts each binary bit of data, that is, turning a 1 into a 0 and a 0 into a 1. Minus x is like minus x minus 1 | (~a) Output result -61, binary interpretation: 1100 0011, in the complement form of a signed binary number. |
<< | Left-shift operator: all binary bits of the operand are shifted to the left by a number of bits. The digit to the right of << is specified by the digit to the left. The higher digit is discarded and the lower digit is compensated by 0. | A << 2 Output 240, binary interpretation: 1111 0000 |
>> | Right shift operator: moves all the binary bits of the operand to the left of “>>” to the right by a number of digits. The digits to the right of >> specify the number of digits to be moved | A >> 2 Output 15, binary interpretation: 0000 1111 |
#! /usr/bin/python # -*- coding: UTF-8 -*- a = 60 # 60 = 0011 1100 b = 13 # 13 = 0000 1101 c = 0 c = a & b; # 12 = 0000, 1100 print "1 - c value is:", c, c = a | b; # 61 = 0011 1101 print "2-c = : ", c c = a ^ b; # 49 = 0011 0001 print "3 -c = : ", c c = ~a; # -61 = 1100 0011 print "4 -c = : ", c c = a << 2; # 240 = 1111 0000 print "5 -c = : ", c c = a >> 2; # 15 = 0000 1111 print "6 -c ", cCopy the code
Logical operator
The operator | Logical expression | describe | The instance |
---|---|---|---|
and | x and y | Boolean “and” – x and y return False if x is False, otherwise it returns a computed value of y. | A and b return 20. |
or | x or y | Boolean “or” – it returns a computed value of x if x is non-zero, otherwise it returns a computed value of y. | (a or b) returns 10. |
not | not x | Boolean “not” – returns False if x is True. If x is False, it returns True. | Not (a and b) returns False |
#! /usr/bin/python # -* -coding: utf-8 -* -a = 10 b = 20 if a and b: print "1 - variable a and b are true" else: Print "1 - variables a and b are not true" if a or b: print "2 - variables a and b are both true, or one of them is true" else: If a and b: print "3 - a and b are both true" else: Print "3 - variables a and b are not true" if a or b: print "4 - variables a and b are both true, or one of them is true" else: Print "4 - both variables a and b are false" if not(a and b): print "5 - both variables a and b are false, or one of them is false" else: Print "5 - variables a and b are true"Copy the code
Member operator
In addition to some of the above operators, Python also supports member operators. Test instances contain a list of members, including strings, lists, or tuples.
The operator | describe | The instance |
---|---|---|
in | Return True if a value is found in the specified sequence, False otherwise. | Return True if x is in the y sequence. |
not in | Return True if no value is found in the specified sequence, False otherwise. | Return True if x is not in the y sequence. |
#! /usr/bin/python # -*- coding: UTF-8 -*- a = 10 b = 20 list = [1, 2, 3, 4, 5 ]; If (a in list): print "1 - variable a is in the list "else: print "1 - variable a is not in the list" if (b not in list): If (a in list) = 2 if (a in list) = 2 if (a in list): Print "3 - variable a is in list "else: print "3 - variable a is not in list"Copy the code
Identity operator
The identity operator is used to compare the storage locations of two objects
The operator | describe | The instance |
---|---|---|
is | Is is to determine whether two identifiers refer to an object | x is y, similar toid(x) == id(y)Returns True if the reference is to the same object, False otherwise |
is not | Is not is to determine whether two identifiers refer to different objects | x is not y, similar toid(a) ! = id(b). Return True if the object is not the same, False otherwise. |
Note: the id() function is used to get the memory address of an object.
#! /usr/bin/python # -* -coding: utf-8 -* -a = 20 b = 20 if (a is b): print "1 -a and b have the same identifier "else: If (a is not b): print "2 -a is not b "else: If (a is b): print "3-a and b have the same id" else: Print "3-a and b are not identical" if (a is not b): print "4-a and b are not identical" else: print "4-a and b are not identical"Copy the code
Is different from == :
Is is used to determine whether the reference objects of two variables are the same (same memory space), and == is used to determine whether the values of the reference variables are equal.
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
>>> b == a
True
>>> b = a[:]
>>> b is a
False
>>> b == a
True
Copy the code
Operator precedence
The operator | describe |
---|---|
支那 | Index (highest priority) |
~ + – | Bitwise inversion, unary plus and minus (the last two methods are called +@ and -@) |
% * / / / | Multiply, divide, modulo and divisor |
+ – | Addition subtraction |
>> << | Shift right, shift left operator |
& | A ‘AND’ |
^ | |
< = < > > = | Comparison operator |
< > = =! = | Equal operator |
= %= /= //= -= += *= **= | Assignment operator |
is is not | Identity operator |
in not in | Member operator |
not and or | Logical operator |
#! /usr/bin/python # -*- coding: Utf-8 -* -a = 20 b = 10 c = 15 d = 5 e = 0 e = (a + b) * c/d #(30 * 15) / 5 print "(a + b) * c/d" ", e e = ((a + b) * c)/d # 5 print "(30 * 15)/(c) (a + b) * / d operation result is:", e e = (a + b) * (c/d); # (30) * (15/5) print "(a + b) * (c/d) calculations for:", e e = a + b * c)/d; # 20 + (150/5) print "a + (b * c)/d"Copy the code
Conditional statements
Remember the end of the colon
If condition 1: Executes statement 1...... Elif Condition 2: Execute statement 2...... Elif Condition 3: Execute statement 3...... Else: Execute statement 4......Copy the code
#! /usr/bin/python # -* -coding: utf-8 -* -num = 5 if num == 3: # print 'boss' elif num == 2: Print 'user' elif num == 1: print 'worker' elif num < 0: # print 'error' else: print 'roadman' #Copy the code
Looping statements
while
While judging a condition: Executing statements...Copy the code
#! /usr/bin/python count = 0 while (count < 9): print 'The count is:', count count = count + 1 print "Good bye!"Copy the code
Loop through the else statement
#! /usr/bin/python count = 0 while count < 5: print count, " is less than 5" count = count + 1 else: print count, " is not less than 5"Copy the code
for
for iterating_var in sequence:
statements(s)
Copy the code
#! /usr/bin/python # -*- coding: UTF-8 -*- for letter in 'Python': Print 'current letter :', letter fruits = ['banana', 'apple', 'mango'] for fruit in fruits: Print 'current fruit :', fruit print "Good bye!"Copy the code
Iterating through a sequence index
#! /usr/bin/python # -*- coding: UTF-8 -*- fruits = ['banana', 'apple', 'mango'] for index in range(len(fruits)): Print 'current fruit :', fruits[index] print "Good bye!"Copy the code
In this example, we used the built-in functions len() and range(). Len () returns the length of the list, i.e. the number of elements. Range returns the number of a sequence.
Loop through the else statement
#! /usr/bin/python # -* -coding: utf-8 -* -coding: utf-8 -* -coding for I in range(2,num): Print '%d '= %d * %d' % (num, I,j) Print num, 'is a prime number'Copy the code
A nested loop
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
while expression:
while expression:
statement(s)
statement(s)
Copy the code
You can embed other loop bodies inside a loop, such as a for loop inside a while loop, or a while loop inside a for loop.
The following example uses a nested loop to output prime numbers between 2 and 100: Instance #! /usr/bin/python # -*- coding: UTF-8 -*- i = 2 while(i < 100): j = 2 while(j <= (i/j)): if not(i%j): Break j = j + 1 if (j > I /j) : print I, "is prime" I = I + 1 print "Good bye!"Copy the code
Break, interrupt the loop
Continue, continue to the next loop
Pass, no operation, in order to maintain the integrity of the program structure. Equivalent to {} in js if(xx){}, null operation
function
Define a function
Def functionname(parameters): "" function_suite return [expression]Copy the code
Def printme(STR): "print the passed string to the standard display device" print STR returnCopy the code
A function call
#! /usr/bin/python # -* -coding: utf-8 -*- # def printme(STR): Print STR return # call function printme(" I want to call a user-defined function!") ) printme(" call the same function again ")Copy the code
Pass immutable object instances
#! /usr/bin/python # -* -coding: utf-8 -* -def ChangeInt(a): a = 10 b = 2 ChangeInt(b) print b #Copy the code
Pass mutable object instances
#! /usr/bin/python # -* -coding: utf-8 -*- # def changeme(mylist): Mylist.append ([1,2,3,4]) print Mylist = [10,20,30] changeme(mylist) printCopy the code
parameter
- Necessary parameters
- Keyword parameter
- The default parameters
- Parameter of indefinite length
Necessary parameters
#! /usr/bin/python # -* -coding: utf-8 -*- # def printme(STR): Print STR return printme() # ErrorCopy the code
Keyword parameter
eg1
#! /usr/bin/python # -* -coding: utf-8 -*- # def printme(STR): Printme (STR = "My string")Copy the code
eg2
#! /usr/bin/python # -* -coding: utf-8 -*- # def printinfo(name, age): "print" name: Printinfo (Age =50, name="miki")Copy the code
The default parameters
#! /usr/bin/python # -* -coding: utf-8 -*- # def printinfo(name, age = 35): "print" name: Printinfo (Age =50, name="miki") printinfo(name="miki")Copy the code
Parameter of indefinite length
Def functionname([formal_args,] *var_args_tuple): "" function_suite return [expression]Copy the code
eg
#! /usr/bin/python # -* -coding: utf-8 -*- # def printinfo(arg1, *vartuple): Printinfo (10) printinfo(70, 60, 50)Copy the code
Anonymous functions
Python uses lambda to create anonymous functions.
- Lambda is just an expression, and the function body is much simpler than def.
- The body of a lambda is an expression, not a block of code. It can only encapsulate a limited amount of logic in a lambda expression.
- Lambda functions have their own namespace and cannot access arguments outside of their own argument list or in the global namespace.
- Lambda functions, while seemingly one-line, are not the same as inline functions in C or C++, which are designed to increase efficiency by calling small functions without taking up stack memory.
lambda [arg1 [,arg2,.....argn]]:expression
Copy the code
#! /usr/bin/python # -* -coding: utf-8 -*- # write sum = lambda arg1, arg2: arg1 + arg2 ", sum(10, 20) print ", sum(20, 20) print"Copy the code
Return statement
#! /usr/bin/python # -* -coding: utf-8 -*- # def sum(arg1, arg2): Total = sum(10, 20)Copy the code
Global variables and local variables
As with js
#! /usr/bin/python # -* -coding: utf-8 -* -total = 0 def sum(arg1, arg2): # return the sum of 2 arguments." total = arg1 + arg2 # Sum (10, 20) print "sum(10, 20) ", totalCopy the code
conclusion
To this, the python finished the minimum necessary knowledge, some people say that object-oriented didn’t speak, date didn’t speak, that I listed in the references, knowledge is necessary for you to run up, the things I can write basic, according to need access to more knowledge into our code, mai main won’t put “plug-in” or unnecessary columns in knowledge.
It’s not a good tutorial to get started if you have to read too much.
Built-in function
Built-in function | ||||
---|---|---|---|---|
abs() | divmod() | input() | open() | staticmethod() |
all() | enumerate() | int() | ord() | str() |
any() | eval() | isinstance() | pow() | sum() |
basestring() | execfile() | issubclass() | print() | super() |
bin() | file() | iter() | property() | tuple() |
bool() | filter() | len() | range() | type() |
bytearray() | float() | list() | raw_input() | unichr() |
callable() | format() | locals() | reduce() | unicode() |
chr() | frozenset() | long() | reload() | vars() |
classmethod() | getattr() | map() | repr() | xrange() |
cmp() | globals() | max() | reverse() | zip() |
compile() | hasattr() | memoryview() | round() | import(a) |
complex() | hash() | min() | set() | |
delattr() | help() | next() | setattr() | |
dict() | hex() | object() | slice() | |
dir() | id() | oct() | sorted() | Exec built-in expressions |
Under the small prestige
- time
- The module
- io
- file
- abnormal
- os
- object-oriented