In python, identifiers are composed of letters, numbers, and underscores.
In python, all identifiers can include English, numbers, and underscores (_), but cannot start with numbers.
#Identifiers in Python are case-sensitive.
#Identifiers starting with an underscore have special meaning. Class attributes starting with a single underscore (_foo) represent class attributes that cannot be accessed directly. They need to be accessed through the interface provided by the class and cannot be imported using "from xxx import *";
(__foo) starting with a double underscore represents the private members of the class; (__foo__) starting and ending with a double underscore represents a special identifier for special methods in python, such as __init__() representing the constructor of the class.
3. python reserved keywords
and
exec
not
assert
finally
or
break
for
pass
class
from
print
continue
global
raise
def
if
return
del
import
try
elif
in
while
else
is
with
except
lambda
yield
4. Python string representation
Python accepts single quotes (' ), double quotes (" ), Triple quotes (''' """) are used to represent strings. The beginning and end of the quotes must be of the same type.
Three quotation marks can be composed of multiple lines, which is a shortcut syntax for writing multi-line text. Commonly used document strings are used as comments at specific locations in the file.
word = 'word'sentence = "这是一个句子。"paragraph = """这是一个段落。
包含了多个语句"""
Copy after login
5. The main annotations in Python are
# or ''' ''' or "" """
6. Python data types:
##Numbers (number
)
{
}
int (signed integer type)
long (long integer type [can also represent octal and hexadecimal])
float (floating point)
complex (plural)
String (string) {
##The plus sign (+) is the string concatenation operator, and the asterisk (*) is the repeat operation:
!/usr/bin/python
# -*- coding: UTF-8 -*-
str = 'Hello World!'
print str # Output complete characters String print str[0] # Output the first character in the string print str[2:5] # Output the third to fifth characters in the string print str[2:] # Output the string starting from the third character print str * 2 # Output the string twice print str + "TEST" # Output the connected string
print list # Output the complete list print list[0] # Output the first element of the list print list[1 :3] # Output the second to third elements print list[2:] # Output all elements from the third to the end of the list print tinylist * 2 # Output the list twice print list + tinylist #Print the combined list
Tuples are marked with "()". Internal elements are separated by commas. But is that the tuple cannot be assigned twice, which is equivalent to a read-only list.
print tuple # Output the complete tuple print tuple[0] # Output the tuple The first element of the group print tuple[1:3] # Output the second to third elements print tuple[2:] # Output all elements starting from the third to the end of the list print tinytuple * 2 # Output the tuple twice print tuple + tinytuple # Print the combined tuple
print dict['one'] # Output the value with key 'one' print dict[2] # Output the value with key 2 print tinydict # Output the complete dictionary print tinydict .keys() # Output all keys print tinydict.values() # Output all values
The output result is:
This is one This is two {'dept': 'sales', 'code': 6734, 'name': 'john'} ['dept', 'code', 'name'] ['sales', 6734, 'john ']
##}
7. Python data type conversion
Function
Description
int(x [ ,base])
Convert x to an integer
##long(x [,base] )
Convert x to a long integer
float(x)
Convert x to a floating point number
complex(real [,imag])
Create a complex number
str(x)
Convert object x to string
repr(x )
Convert object x to expression string
##eval(str)
Used to evaluate a valid Python expression in a string and return an object
tuple(s)
Convert sequence s into a tuple
list(s)
Convert Sequence s is converted into a list
set(s)
Convert to a variable set
dict(d)
Create a dictionary. d must be a sequence of (key, value) tuples.
frozenset(s)
Convert to immutable collection
chr(x)
Convert an integer to a character
unichr( x)
Convert an integer to Unicode characters
##ord(x)
Convert a character to its integer value
hex(x)
Convert an integer to a hexadecimal string
oct(x)
Convert an integer to an octal string
8. Python’s operators
Python’s arithmetic operators
+
Add - Add two objects
a + b Output result 30
-
Subtract - Get a negative number or one number minus another number
a - b Output result-10
*
Multiply - Multiply two numbers or return a string repeated several times
a * b Output result 200
/
Division - x divided by y
b / a Output result 2
##%
Modulo- Returns the remainder of division
b % a Output result 0
**
Power - Returns the y power of x
a**b is 10 raised to the 20th power, and the output result is 100000000000000000000
//
Return the integer part of the quotient
9/ /2 Output result 4, 9.0//2.0 Output result 4.0
Python comparison operators
##Operator
Description
Example
==
Equal - Compare objects for equality
(a == b) Return False.
!=
Not equal to - Compares whether two objects are not equal
(a != b) Returns true.
<>
Not equal to - Compares whether two objects are not equal
(a <> b) Returns true. This operator is similar to != .
>
Greater than - Returns whether x is greater than y
(a > b) Returns False.
<
Less than - Returns whether x is less than y. All comparison operators return 1 for true and 0 for false. These are equivalent to the special variables True and False respectively. Note the capitalization of these variable names.
(a < b) returns true.
>=
Greater than or equal to - Returns whether x is greater than or equal to y.
(a >= b) Returns False.
<=
Less than or equal to - Returns whether x is less than or equal to y.
(a <= b) returns true.
Python’s assignment operator
##Operator
Description
Example
=
Simple assignment operator
c = a + b assigns the operation result of a + b For c
+=
the additive assignment operator
c += a is equivalent to c = c + a
-=
Subtractive assignment operator
c -= a is equivalent to c = c - a
*=
Multiplication assignment operator
c *= a is equivalent to c = c * a
##/=
Division assignment operator
c /= a is equivalent to c = c / a
##%=
modulo assignment operator
c %= a Equivalent to c = c % a
**=
Power assignment operator
c **= a Equivalent to c = c * * a
##//=
Take the integer division assignment operator
c //= a is equivalent to c = c // a
python bitwise operators
#Operator
Description
Example
&
Bitwise AND operator: Two values participating in the operation. If both corresponding bits are 1, then the bit The result is 1, otherwise it is 0
(a & b) The output result is 12, binary interpretation: 0000 1100
##|
bitwise OR Operator: As long as one of the two corresponding binary bits is 1, the result bit is 1.
(a | b) The output result is 61, binary interpretation: 0011 1101
##^
Bitwise XOR operator: when two corresponding When the binary bits are different, the result is 1
(a ^ b) and the output result is 49. Binary interpretation: 0011 0001
~
bitwise Negation operator: Negate each binary bit of the data, that is, change 1 to 0, and change 0 to 1
(~a) The output result is -61, binary interpretation: 1100 0011, in a The two's complement form of a signed binary number.
##<<
Left shift operator: Each binary digit of the operand is shifted to the left by a certain number of bits, specified by the number on the right of "<<" The number of digits to move, the high bits are discarded, and the low bits are filled with 0s.
a << 2 The output result is 240, binary interpretation: 1111 0000
>>
Right shift operator: " >>"All binary digits of the operand on the left are shifted to the right by a certain number of digits,">>"The number on the right specifies the number of digits to move
a >> 2 The output result is 15, binary Explanation: 0000 1111
python logical operators
##Operator
Logical expression Formula
Description
Example
and
x and y
Boolean "AND" - if x If False, x and y return False, otherwise it returns the calculated value of y.
(a and b) returns 20.
or
x or y
Boolean "or" - if x is True, it returns True, otherwise it returns the calculated value of y.
(a or b) returns 10.
not
not x
Boolean "not" - If x is True, returns False. If x is False, it returns True.
not(a and b) returns False
Member operators of python
##Operator
Description
Example
in
Returns True if the value is found in the specified sequence, False otherwise.
x is in the y sequence, returns True if x is in the y sequence.
not in
Returns True if the value is not found in the specified sequence, False otherwise.
x is not in the y sequence, returns True if x is not in the y sequence.
Priority of python
**
Index (highest priority)
##~ + -
Bitwise flip , unary plus sign and minus sign (the last two methods are named +@ and -@)
* / % //
Multiplication, division, modulo Sum and division
+ -
Addition and subtraction
>> <<
Right shift, left shift operator
&
bit 'AND'
^ |
bit operator
<= < > >=
Comparison operator
<> ; == !=
Equal operator
= %= /= //= -= += *= **=
Assignment Operator
is is not
Identity operator
##in not in
Membership operator
not or and
logical operators
Python’s mathematical functions
Function
Return value (description)
abs(x)
Returns the absolute value of the number Value, such as abs(-10) returns 10
ceil(x)
Returns the upper integer of the number, such as math.ceil(4.1) returns 5
cmp(x, y)
If x < y returns -1, if x == y returns 0, if x > y returns 1
exp(x)
Returns the x power of e (ex), such as math.exp(1) returns 2.718281828459045
fabs(x)
Returns the absolute value of the number, such as math.fabs(-10) returns 10.0
floor(x)
Return the rounded integer of the number, such as math.floor(4.9) returns 4
log(x)
For example, math.log(math.e) returns 1.0, math.log(100,10) returns 2.0
log10(x)
Returns the logarithm of x with base 10 as the base, such as math.log10( 100) Return 2.0
max(x1, x2,...)
Returns the maximum value of the given parameter, and the parameter can be a sequence.
min(x1, x2,...)
Returns the minimum value of the given parameter, which can be a sequence.
modf(x)
Returns the integer part and decimal part of x. The numerical signs of the two parts are the same as x, and the integer part is expressed in floating point type.
pow(x, y)
x**y Value after operation.
round(x [,n])
Returns the rounded value of the floating point number x. If the n value is given, it represents the number of digits rounded to the decimal point. .
sqrt(x)
Returns the square root of the number x. The number can be negative and the return type is real number. For example, math.sqrt(4) returns 2+0j
python random function
Random numbers can be used in mathematics, games, security and other fields, and are often embedded in algorithms , to improve algorithm efficiency and improve program security.
Python contains the following commonly used random number functions:
Function
Description
choice (seq)
Randomly select an element from the elements of the sequence, such as random.choice(range(10)), randomly select an integer from 0 to 9.
randrange ([start,] stop [,step])
Get a random number from the set in the specified range, incremented by the specified base, the base is default The value is 1
random()
Randomly generates the next real number, which is in the range [0,1).
seed([x])
Change the seed of the random number generator. If you don't understand the principle, you don't have to set the seed specifically, Python will choose the seed for you.
shuffle(lst)
Randomly sort all elements of the sequence
uniform(x, y)
Randomly generate the next real number, which is in the range [x, y].
Trigonometric functions of python
Number
Description
##acos(x)
Return the arc cosine radians value of x.
asin(x)
Returns the arcsine radians value of x.
atan(x)
Returns the arctangent radian value of x.
atan2(y, x)
Returns the arctangent of the given X and Y coordinate values.
cos(x)
Returns the cosine of x in radians.
##hypot(x, y)
Returns the Euclidean norm sqrt(x*x + y*y) .
sin(x)
Returns the sine value of x radians.
tan(x)
Returns the tangent of x in radians.
degrees(x)
Convert radians to degrees, such as degrees(math.pi/2), return 90.0
radians(x)
Convert angles to radians
Python's built-in string functions
##Method
Description
string.capitalize()
Put the first string uppercase characters
##string.center(width)
Returns an original string centered and filled with spaces New string to length width
##string.count(str, beg=0, end=len(string))
Returns the number of times str appears in string. If beg or end is specified, returns the number of times str appears in the specified range.
string.decode(encoding='UTF-8', errors='strict')
Decode string in the encoding format specified by encoding. If an error occurs, a ValueError exception will be reported by default, unless errors specify 'ignore' or 'replace'
string.encode(encoding='UTF-8', errors='strict')
The encoding specified by encoding Format encoding string, if an error occurs, a ValueError exception will be reported by default, unless errors specify 'ignore' or 'replace'
string.endswith( obj, beg=0, end=len(string))
Check whether the string ends with obj. If beg or end is specified, check whether the specified range ends with obj. End, if yes, return True, otherwise return False.
##string.expandtabs(tabsize=8)
Convert the tab symbol in the string string to spaces. The default number of spaces for the tab symbol is 8.
##string.find(str, beg=0, end=len(string))
Check whether str is included in string. If beg and end specify the range, check whether it is included in the specified range. If it is, return the starting index value, otherwise return -1
string.index(str, beg=0, end=len(string))
The same as the find() method, only However, if str is not in string, an exception will be reported.
string.isalnum()
Returns ## if string has at least one character and all characters are letters or numbers
#Return True, otherwise return False
string.isalpha()
If string has at least one character and all characters are letters, return True, Otherwise, return False
##string.isdecimal()
Returns True if string contains only decimal digits, otherwise returns False.
##string.isdigit()
If string only contains numbers, return True otherwise return False.
##string.islower()
Returns True if string contains at least one case-sensitive character and all of these (case-sensitive) characters are lowercase, otherwise False
string.isnumeric()
If the string contains only numeric characters, return True, otherwise return False
##string.isspace()
If the string contains only spaces, return True, otherwise return False.
##string.istitle()
Returns True if string is titled (see title()), otherwise returns False
string.isupper( )
Returns True if string contains at least one case-sensitive character and all these (case-sensitive) characters are uppercase, otherwise it returns False
string.join(seq)
Using string as the separator, join all elements in seq (String representation) merged into a new string
string.ljust(width)
Return A new string that aligns the original string to the left and pads it with spaces to length width
##string.lower()
Convert all uppercase characters in string to lowercase.
##string.lstrip()
Truncate the spaces to the left of string
##string.maketrans(intab, outtab])
maketrans( ) method is used to create a conversion table for character mapping. For the simplest calling method that accepts two parameters, the first parameter is a string representing the character that needs to be converted, and the second parameter is also the string representing the target of conversion.
max(str)
Returns the largest letter in the string
str
.
min(str)
Returns the smallest letter in the string
str
.
##string.partition(str)
A bit like find() and split( ), starting from the first position where str appears, divide the string string into a 3-element tuple (string_pre_str, str, string_post_str). If string does not contain str, then string_pre_str == string.
Replace str1 in string with str2. If num is specified, the replacement will not exceed num times.
string.rfind(str, beg=0,end= len(string) )
Similar to the find() function, but starting from the right.
string .rindex(str, beg=0,end=len(string))
Similar to index(), but starts from the right.
string.rjust(width)
Returns a new string with the original string right-aligned and padded with spaces to length width
string.rpartition(str)
Similar to the partition() function, but starts searching from the right.
string.rstrip()
Remove string spaces at the end of the string.
string.split(str="", num=string.count(str))
Use str as the delimiter to slice string. If num has a specified value, only num substrings will be separated.
##string.splitlines(num=string.count( '\n'))
Separated by row, return a list containing each row as an element. If num is specified, only num rows will be sliced.
string.startswith(obj, beg=0,end=len(string))
Check whether the string starts with obj, if so, return True, otherwise returns False. If beg and end specify values, check within the specified range.
string.strip([obj])
Execute lstrip() and rstrip() on string
##string.swapcase()
Reverse case in string
string.title()
Returns a "titled" string, that is, all words start with uppercase letters, and the remaining letters are lowercase (see istitle())
string.translate(str, del="")
Convert string according to the table (containing 256 characters) given by str Characters,
Put the characters to be filtered out in the del parameter
string.upper()
Convert the lowercase letters in string to uppercase
string.zfill(width)
The return length is The string of width, the original string string is right-aligned, and the front is filled with 0
string.isdecimal()
The isdecimal() method checks whether a string contains only decimal characters. This method only exists for unicode objects.
Python's List function
##Serial number
Function
1
cmp(list1, list2)
Compare the elements of two lists
2
len(list)
Number of list elements
3
max(list)
Returns the maximum value of list elements
4
min(list)
Returns the minimum value of the list element
5
list(seq)
Convert tuple to list
Python contains the following methods:
Serial number
Method
1
list.append(obj) Add a new object at the end of the list
2
list.count(obj) Count the number of elements in the list The number of occurrences in
3
list.extend(seq) Append multiple values from another sequence at the end of the list at once (use a new list Expand the original list)
4
list.index(obj) Find the index position of the first matching item of a value from the list
5
list.insert(index, obj) Insert object into the list
6
list.pop(obj=list[-1]) Remove an element in the list (the last element by default) and return the value of the element
7
list.remove(obj) Remove the first occurrence of a value in the list
8
list.reverse () Elements in the reverse list
9
list.sort([func]) Sort the original list
Python tuples’ built-in functions
The Python tuple contains the following built-in functions
Serial number
Method and description
1
cmp(tuple1, tuple2) Compare two tuple elements.
2
len(tuple) Calculate the number of tuple elements.
3
max(tuple) Returns the maximum value of the element in the tuple.
4
min(tuple) Returns the minimum value of the element in the tuple.
5
tuple(seq) Convert the list to a tuple.
Dictionary built-in functions & methods
Python dictionary contains the following built-in functions:
Serial number
Function and description
1
cmp(dict1, dict2) Compares two dictionary elements.
2
len(dict) Calculate the number of dictionary elements, that is, the total number of keys.
3
str(dict) Output the printable string representation of the dictionary.
4
type(variable) Returns the input variable type. If the variable is a dictionary, returns the dictionary type.
Python dictionary contains the following built-in methods:
Serial number
Function and description
1
radiansdict.clear() Delete all elements in the dictionary
2
radiansdict.copy() Return a dictionary Copy
3
radiansdict.fromkeys() Create a new dictionary, using the elements in the sequence seq as the keys of the dictionary, and val is the value corresponding to all keys in the dictionary Initial value
4
radiansdict.get(key, default=None) Returns the value of the specified key, if the value is not in the dictionary, returns the default value
5
radiansdict.has_key(key) Returns true if the key is in the dictionary dict, otherwise returns false
6
radiansdict.items() Returns a traversable (key, value) tuple array as a list
7
radiansdict. keys() Returns all the keys of a dictionary in a list
8
radiansdict.setdefault(key, default=None) and get() Similar, but if the key does not exist in the dictionary, the key will be added and the value will be set to default
9
radiansdict.update(dict2) Put The key/value pairs of dictionary dict2 are updated into dict
10
radiansdict.values() Return all values in the dictionary as a list
Python 日期和时间
thon 程序能用很多方式处理日期和时间,转换日期格式是一个常见的功能。
Python 提供了一个 time 和 calendar 模块可以用于格式化日期和时间。
时间间隔是以秒为单位的浮点小数。
每个时间戳都以自从1970年1月1日午夜(历元)经过了多长时间来表示。
Python 的 time 模块下有很多函数可以转换常见日期格式。如函数time.time()用于获取当前时间戳, 如下实例:
以下输出2016年1月份的日历:
January 2016Mo Tu We Th Fr Sa Su
1 2 3
4 5 6 7 8 9 1011 12 13 14 15 16 1718 19 20 21 22 23 2425 26 27 28 29 30 31
Copy after login
Time 模块
Time 模块包含了以下内置函数,既有时间处理相的,也有转换时间格式的:
Serial number
Function and description
1
time.altzone Return to Greenway The offset in seconds for the western daylight saving time zone. Negative values are returned if the area is east of Greenwich (such as Western Europe, including the UK). Available only in regions where daylight saving time is enabled.
2
time.asctime([tupletime]) Accepts a time tuple and returns a readable form of "Tue Dec 11 18:07: 14 2008" (Tuesday, December 11, 2008 18:07:14) is a 24-character string.
3
time.clock( ) Returns the current CPU time in seconds calculated as a floating point number. It is used to measure the time consumption of different programs and is more useful than time.time().
4
time.ctime([secs]) The function is equivalent to asctime(localtime(secs)). No parameters are given, which is equivalent to asctime()
5
time.gmtime([secs]) Receives the timeout (the number of floating point seconds elapsed since the 1970 epoch) and returns Greenwich astronomical time The time tuple under t. Note: t.tm_isdst is always 0
6
time.localtime([secs]) Receive time (floating point seconds elapsed after 1970 epoch number) and returns the time tuple t in local time (t.tm_isdst can be 0 or 1, depending on whether the local time is daylight saving time).
7
time.mktime(tupletime) Accepts a time tuple and returns the timeout (the number of floating point seconds elapsed since epoch 1970).
8
time.sleep(secs) Delay the running of the calling thread, secs refers to the number of seconds.
9
time.strftime(fmt[,tupletime]) Receives a time tuple and returns the local time as a readable string in a format determined by fmt.
10
time.strptime(str,fmt='%a %b %d %H:%M:%S %Y') According to The format of fmt parses a time string into a time tuple.
11
time.time( ) Returns the timestamp of the current time (the number of floating-point seconds elapsed since epoch 1970).
12
time.tzset() Reinitialize time-related settings according to the environment variable TZ.
The Time module contains the following two very important attributes:
Serial Number
Attribute And description
1
time.timezone The property time.timezone is the local time zone (without daylight saving time) distance from Greenwich Offset seconds (>0, Americas; <=0 most of Europe, Asia, Africa).
2
time.tzname The attribute time.tzname contains a pair of strings that vary depending on the situation, namely The local time zone name with and without daylight saving time.
Calendar module
The functions of this module are all calendar-related, such as printing the character calendar of a certain month.
Monday is the default first day of the week, and Sunday is the default last day. To change the settings, you need to call the calendar.setfirstweekday() function. The module contains the following built-in functions:
Serial number
Function and description
1
calendar.calendar(year, w=2,l=1,c=6) Returns a year calendar in multi-line string format, with 3 months per line and an interval of c. Daily width interval is w characters. The length of each line is 21* W+18+2* C. l is the number of lines per week.
2
calendar.firstweekday( ) Returns the setting of the current weekly starting day. By default, 0 is returned when the caendar module is first loaded, which is Monday.
3
calendar.isleap(year) returns True if it is a leap year, otherwise false.
4
calendar.leapdays(y1,y2) Returns the total number of leap years between Y1 and Y2.
5
calendar.month(year,month,w=2,l=1) Returns a multi-line string The calendar format is year and month, with two rows of titles and one row for each week. Daily width interval is w characters. The length of each line is 7* w+6. l is the number of lines per week.
6
calendar.monthcalendar(year,month) Returns a single-level nested list of integers. Each sublist holds an integer representing a week. Dates outside Year, month, and month are all set to 0; days within the range are represented by the day of the month, starting from 1.
7
calendar.monthrange(year,month) Returns two integers. The first is the date code of the day of the week of the month, and the second is the day code of the month. Days range from 0 (Monday) to 6 (Sunday); months range from 1 to 12.
8
calendar.prcal(year,w=2,l=1,c=6) is equivalent to print calendar .calendar(year,w,l,c).
9
##calendar.prmonth(year,month,w=2,l=1) Equivalent to print calendar.calendar(year, w, l, c).
10
calendar.setfirstweekday(weekday) Set the starting day code of each week. 0 (Monday) to 6 (Sunday).
11
calendar.timegm(tupletime) The opposite of time.gmtime: accepts a time tuple form and returns the time The time of day (the number of floating point seconds elapsed since the 1970 epoch).
12
calendar.weekday(year,month,day) Returns the date code of the given date. 0 (Monday) to 6 (Sunday). Months range from 1 (January) to 12 (December).
Other related modules and functions
In Python, other modules for processing dates and times are:
datetime module
pytz module
dateutil module
The above is the detailed content of Python basic syntax encyclopedia. For more information, please follow other related articles on the PHP Chinese website!
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn