【Python】Basics - Variables

Posted by 西维蜀黍 on 2019-09-19, Last Modified on 2024-05-02

Assignment statement

Assignment statement gives a value to a variable:

  • assignment token: =
  • equals: ==

Ask the interpreter to evaluate a variable

Variable names

Variable name can contain letters, digits and underscore character (""), but they have to begin with e letter or underscore ("").

If you give a variable a illegal name, you get a syntax error:

Here, Python keywords are defined as the language’s syntax rules and structure and thus cannot be used as variable names.

Python keywords

Statement

  • assignment statement: =

Evaluating expressions

An expression is a combination of values, variables, operators.

If you type an expression at the Python prompt, the interpreter evaluates it and displays the result.

Operators and operands

Operators are special tokens that represent computations like addition, multiplication and division. The values the operator uses are called operands.

Operators

  • addition: +
  • subtraction: -
  • multiplication: *
  • division: /
  • exact division(整除): //
  • modulus(求余): %
  • exponentiation(指数): **

Type converter functions

  • int()
  • str()
  • float()

Truncation towards zero: for floating point numbers, it discards the decimal portion of the number.

int function: floating point number or string -> int


When we try to covert a string which is not a number, Python interpreter will show a Value Error:

When we try to covert a string which is a floating point number, rather a whole number, Python interpreter will also show a Value Error:

When we covnert a negative floating point number to a whole number, the result will be closer to zero.

Rules of precedence

Python follows the same precedence rules for its mathematical operators that mathematics does.

Reference

  • Learning Python
  • Python Crash Course (2nd Edition) : A Hands-On, Project-Based Introduction to Programming