Python basic notes and python notes
1. Environment variable settings:
Edit the system variable Path and add two new paths.
C: \ Python26 can be used to call python.exe.
C: \ python26 \ Scripts calls third-party Scripts added to Python through extension.
2. If you use Chinese characters, the character set must be specified in the first line of the py file:
#-*-Coding: UTF-8 -*-
Or
# Encoding: UTF-8
3. Variable Length Parameter
4. Use global variables
You can use the global keyword before a variable name.
A = 5
Def fun (x ):
Global
Return x +
5. lambda expressions
Anonymous function, single-row small function
Format: labmda parameter: Expression
Returns the value of the expression.
It can contain a single parameter expression and cannot contain statements, but can call other functions.
Fun = lambda x: x * x-x
Fun (3)
Def show ():
Print 'lambda'
F = lambda: show ()
F ()
Def shown (n ):
Print 'lambda '* n
Fn = lambda x: shown (x)
Fn (2)
6. run scripts
Python code
- # Encoding = UTF-8
- Def show ():
- Print u' I am a module .'
- If _ name _ = '_ main __':
- Show ()
7. Random Number
Import random
Random. random () # generate a random floating point number [)
Random. randint (a, B) # generate an integer between [a, B] (including a and B)
8. input parameters in the command line
Def prompt (prompt ):
Return raw_input (prompt). strip ()
Name = prompt ("Your Name :")
9. Python characters
In python, the character is a string of 1.
Obtain all characters of a string:
Python code
- >>> String = 'abcxyz'
- >>> Char_list = list (string)
- >>> Print char_list
- ['A', 'B', 'C', 'x', 'y', 'z']
- >>> Char_list = [c for c in string]
- >>> Print char_list
- ['A', 'B', 'C', 'x', 'y', 'z']
- >>># Obtain a set of all characters of a string
- >>> Import sets
- >>> Char_set = sets. Set ('abbcc ')
- >>> Print char_set
- Set (['A', 'C', 'B'])
- >>> Print ','. join (char_set)
- A, c, B
- >>> Type (char_set)
- <Class 'sets. set'>
- >>> For c in char_set:
- Print c
- A
- C
- B
10. Conversion of characters and character values
Converts a character to an ascii code. The built-in function ord ():
>>> Ord ('A ')
97
Convert ascii code to character. built-in function chr ():
>>> Chr (97)
'A'
Convert unicode characters to unicode codes. The built-in function ord ():
>>> Ord (U' \ u2020 ')
8224
Converts a unicode code to a unicode character. The built-in function unichr ():
>>> Unichr (8224)
U' \ u2020'
11. test whether the object is a class string
Isinstance (anobj, basestring)
12. sys. argv
List of command line parameters passed to the Python script. Argv [0] is the script name.
Python code
- # _ * _ Coding: UTF-8 _*_
- Import sys
- If _ name _ = "_ main __":
- If len (sys. argv) <2:
- Print "Need a argument! "
- Sys. exit (1)
- Arg = sys. argv [1]
- Print 'you input a argument: ', arg