Skip to main content

Basic Grammar

Data types

  • Integer: Python can handle integers of arbitrary size (Python 2.x had two types of integers, int and long, but this distinction is not very meaningful for Python, so in Python 3.x integers are now only int), and supports binary (e.g. 0b100, which converts to decimal as 4), octal (e.g. 0o100, which translates to 64 in decimal), decimal (100) and hexadecimal (0x100, which translates to 256 in decimal) representations.

  • Floating point: Floating point numbers are also known as decimals, so called because the position of the decimal point of a floating point number is variable when expressed in scientific notation, and floating point numbers support scientific notation (e.g. 1.23456e2) in addition to mathematical writing (e.g. 123.456).

  • Strings: Strings are arbitrary text enclosed in single or double quotes, such as 'hello'' and "hello"`, strings are also available in raw string representation, byte string representation, Unicode string representation and can be written in multi-line form (starting with three single or three double quotes and ending with three single or three double quotes).

  • Boolean: Boolean values have only two values, True and False, either True or False. In Python, Boolean values can be expressed directly as True and False (please note the case), or they can be calculated by Boolean operations (e.g. 3 < 5 produces the Boolean value True, while 2 == 1 will produce the Boolean value False).

  • The complex type: shaped as 3 + 5j is the same as the mathematical representation of a complex number, the only difference being that the i in the imaginary part is replaced by j. In fact, this type is not commonly used, so it is good to know about it.

Variable naming

Hard and fast rules:

  • Variable names consist of letters (broad Unicode characters, excluding special characters), numbers and underscores; numbers cannot begin.
  • Case sensitive (an upper case a and a lower case A are two different variables).
  • Do not conflict with keywords (words with special meanings, covered later) and system reserved words (e.g. names of functions, modules, etc.).

PEP 8 requires:

  • Spell words in lowercase letters, with multiple words connected by underscores.
  • Protected instance attributes begin with a single underscore (covered later).
  • Private instance attributes begin with two underscores (more on this later).

Using type() to check the type of a variable

The built-in functions in Python perform conversions on variable types.

  • int(): converts a numeric value or string to an integer, you can specify the binary.
  • float(): converts a string to a floating point number.
  • str(): converts a specified object to string form, with the possibility of specifying an encoding.
  • chr(): converts an integer to the string corresponding to that encoding (one character).
  • ord(): converts a string (a character) into the corresponding encoding (an integer).

Operators

operatordescription
[] [:]subscript, slice
*exponentiation
~ + -Inverse by bit, plus or minus sign
* / % /multiply, divide, modulo, integer division
+ -add, subtract
> <<shift right, shift left
&by bit with
^ ``
<= < > >=less-than-equal, less-than, greater-than, greater-than-equal
== `! =``equal to, not equal to
is is notidentity operator
in not inmember operators
not or andlogical operators
= += -= *= /= %= //= **= &= `= ^= >>= <<=`
  • In practical development, if you are confused about the precedence of operators, you can use parentheses to ensure that the operations are executed in order. *

Keyword

keyworddescription
andLogical operators.
asCreate an alias.
assertUsed for debugging.
breakexit the loop.
classDefines a class.
continueContinue to the next iteration of the loop.
defDefines a function.
delDelete the object.
elifUsed in conditional statements, equivalent to else if.
elseUsed in conditional statements.
exceptHandles exceptions and how to execute them if they occur.
FalseBoolean value, the result of a comparison operation.
finallyHandles exceptions, and executes a piece of code whether or not an exception exists.
forCreates a for loop.
fromImport a specific part of the module.
globalDeclare global variables.
ifWrite a conditional statement.
importImporting a module.
inCheck if a value exists in a collection such as a list, tuple, etc.
isTests if two variables are equal.
lambdaCreate anonymous functions.
NoneIndicates a null value.
nonlocalDeclares a non-local variable.
notThe logical operator.
orThe logical operators.
passnull statement, a statement that does nothing.
raiseRaises an exception.
returnQuit the function and return the value.
TrueBoolean, the result of a comparison operation.
tryWrite try... ...except statements.
whileCreate a while loop.
withis used to simplify exception handling.
yieldends the function and returns the generator.

Comments

  • Single line comments: those starting with # and a space

  • Multi-line comments: three quotes at the beginning and three quotes at the end

"""
First Python program - hello, world!
A tribute to the great Dennis M. Ritchie
Version: 0.1
Author: ``Luo Hao
"""
# hello world!
print('hello, world!')
print("hello, world!")