unless specified otherwise, all materials are from the tutorial provided by w3school: Python Tutorial
目录
Syntax
Indentation
(probably a feature for newer python versions)
the indentation does not need to be consistent (though, serious just keep them the same!),
except for within the same block (scope under a keyword or a function definition).
Comment
for single line, use "#";
for multiple line: Since Python will ignore string literals that are not assigned to a variable, you can add a multiline string (triple quotes) in your code, and place your comment inside it:
E.X.
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
Variable
1. no declaration of variable possible; variable created when assigned a value (defined and declared).
2. variable names conform to C/CPP standard, i.e. starting with '_' or alpha, case sensititve etc.
Assigning Values
Python allows you to assign values to multiple variables in one line:
Example mul to mul
x, y, z = "Orange", "Banana", "Cherry"
And you can assign the same value to multiple variables in one line:
Example one to mul
x = y = z = "Orange"
Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows you extract the values into variables. This is called unpacking.
Example
Unpack a list:
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
Output Variables
The Python print
statement is often used to output variables.
To combine both text and a (string) variable, Python uses the +
character:
Example
x = "awesome"
print("Python is " + x)
"+" handles addition of both numerical and textual data as in CPP; mixture not supported.
The global Keyword
Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function.
To create a global variable inside a function, you can use the global
keyword.
Example
If you use the global
keyword, the variable belongs to the global scope:
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
Also, use the global
keyword to change a global variable inside a function.
x = "awesome"
def myfunc():
global x
x = "fantastic"
DataTypes
==> !!! note that we use different brakets for each collection datatype when defining the variable by assigning value:
while if we use the constructor, the standardized options all allow use of TUPLE:
except for dict(), where enumeration by ',' are favored.
Bool
the binary values for boolean variables are:
True/False
The bool()
function allows you to evaluate any value, and give you True
or False
in return
==> bool(0) gives False, as per general convention.
Int
==> no overflow, the length of an int can be unlimited ==> though it comes at a performance cost
==> float to int is by default (casting) a truncation (or round down).
MemoryView (python pointer !)
from: https://docs.python.org/3/library/stdtypes.html#memoryview
memoryview
objects allow Python code to access the internal data of an object that supports the buffer protocol without copying.
so a pointer, really;
use the object to get access to successive data by memory address and offset as discussed below:
A memoryview
has the notion of an element, which is the atomic memory unit handled by the originating object. For many simple types such as bytes
and bytearray
, an element is a single byte, but other types such as array.array
may have bigger elements.
>>> v = memoryview(b'abcefg')
>>> v[1]
98
>>> v[-1]
103
>>> v[1:4]
<memory at 0x7f3ddc9f4350>
>>> bytes(v[1:4])
b'bce'
Bytes vs. Bytearray
Bytes objects are immutable sequences of single bytes. Since many major binary protocols are based on the ASCII text encoding, bytes objects offer several methods that are only valid when working with ASCII compatible data and are closely related to string objects in a variety of other ways.
bytes can be defined as:
x = b"Hello"
the string literals were used to set the values of each byte within the "bytes"
bytearray
objects are a mutable counterpart tobytes
objects.bytearray can be declared with null initial (default) values:
x = bytearray(5)
for non-byte objects:
>>> import array
>>> a = array.array('l', [-11111111, 22222222, -33333333, 44444444])
>>> m = memoryview(a)
>>> m[0]
-11111111
>>> m[-1]
44444444
>>> m[::2].tolist()
[-11111111, -33333333]
Complex
either use the cmath library for complex(x, y), or use:
x = 1+1j
#display x:
print(x)
#display the data type of x:
print(type(x))
use "j, instead of the more commonly used "i"
Casting
If you want to specify the data type of a variable, this can be done with casting.
Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types.
Casting in python is therefore done using constructor functions:
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
casting can be important when performances are concerned, since type fluidity comes at the cost of run time type checking/scanning.
You can get the data type of a variable with the type()
function.
e.g.
x = 5
y = "John"
print(type(x)) # <class 'int'>
print(type(y)) # <class 'str'>