Chapter 2 Fundamentals of Python

107
Chapter 2 Fundamentals of Python Zhou Rong [email protected] North China Electric Power University Control & Computer Engineering School

Transcript of Chapter 2 Fundamentals of Python

Page 1: Chapter 2 Fundamentals of Python

Chapter 2 Fundamentals of Python

Zhou [email protected]

North China Electric Power UniversityControl & Computer Engineering School

Page 2: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

2

10/7/2021

Outline

2.1 Python programs overview2.2 Identifier and its naming rules2.3 Python objects and references2.4 Data type2.5 Operators and expressions 2.6 Statements2.7 Functions and modules2.8 Output and Input

Page 3: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University2.1 Python programs overview

3

10/7/2021

Page 4: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

【Example 2.1】 Calculate the area of a trianglen Given the three sides of a triangle, find the

area of the triangle (area.py). n Tips:assuming that the three sides are a, b

and c respectively, the area of the triangle is s= . Where h is half the circumference of the triangle

4

10/7/2021

)ch(*b)h(*)ah(*h

import math # Import statement to import math modulea = 3.0;b = 4.0;c = 5.0 #Assignment statement,bind variable to objecth = (a + b + c) / 2 #Expression statements = math.sqrt(h*(h-a)*(h-b)*(h-c)) #Call module math’s functionprint(s) # Built in function calling. Output the Area of triangle

Page 5: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Python Program Composition-from structure view

n Python programs can be broken down into modules, statements, expressions.Conceptually, the corresponding relationship is as follows:

(1)The python program consists of modules corresponding to the source file with the extension. py. A Python program consists of one or more modules. (2)Modules consist of statements. A module is a python source file. When running a python program, execute the statements in sequence according to the statement order in the module.

5

10/7/2021

Page 6: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Python Program Composition(3)Statement is block of Python code, which is used to create objects, assign variables, call functions, control branches, create loops, add comments, ect. (4)Expressions are used to create and process objects.

6

10/7/2021

Page 7: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Python Program Composition- from functional view

IPO:

(1)Input ¨Input is the beginning of a program. The data to

be processed has a variety of sources, forming a variety of input methods, including interactive input, parameter input, random data input, file input, network input and so on.

7

10/7/2021

Input Processing Output

Page 8: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Python Program Composition- from functional view

IPO:

(2)Program processing ¨Processing is the process in which a program

computes input data to produce an output. Methods of solving computational problems are collectively called "algorithms".

8

10/7/2021

Input Processing Output

Page 9: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Python Program Composition- from functional view

IPO:

(3)Output ¨Output is results. The output mode of the

program includes console output(including text ,graphics audio and video), file output, network output and so on

9

10/7/2021

Input Processing Output

Page 10: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University2.2 Identifier and its naming rules

10

10/7/2021

Page 11: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

n Identifiers are the names of variables, functions, classes, modules, and other objects.

n The first character of the identifier must be a letter, an underscore (“_"), The characters that follow can be letters, underscores or numbers.

n Some special names, such as if, for and other reserved keywords, cannot be used as identifiers.

n For example, a_ int、a_ float、str1、_strname and func1 are correct variable names; 99var, it's OK and for (keywords) are wrong variable names.

Page 12: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Attention

(1) Python identifiers are case sensitive. For example, ABC and abc are considered different names. ABC is used as symbolic constant and abc is used as variable.(2)Names that begin and end with double underscores usually have special meanings. For example, __init__ is the constructor of a class, which should generally be avoided.(3)Avoid using Python predefined identifier names as custom identifier names. For example, Notlmplemented, ellipses, int, float, list, str, tuple, etc.

Page 13: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Reserved keywordsn Keywords are predefined reserved identifiers.n Keywords cannot be used as identifiers in programs, otherwise

compilation errors will occur.

【Example 2.11】Viewing keywords using the python help system>>> help()help> keywordshelp> ifhelp> quit

Page 14: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Python predefined identifier

n Python language contains many predefined built-in classes, exceptions, functions, etc, such as float, ArithmeticsError, print, etc.

n Users should avoid using Python predefined identifier names as custom identifier names.

n Use Python's built-in function dir(__builtins__), view all built-in exception names, function names, etc.

Page 15: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Naming rules for Python language

Type Naming rules ExamplesM o d u l e / p a c k a g e name

All lowercase letters, simple and meaningful, underscore could be used if necessary. math、sys

Function name

All lowercase letters and underscore to increase readability. foo(), my_func()

Variable name

All lowercase letters and underscore to increase readability. age、my_var

Class name

Pascalcase naming rules are adopted, that is, multiple words form a name. Except the first letter of each word is capitalized, the other letters are lowercase.

MyClass

Constant name All capital letters and underscore to increase readability.

L E F T 、TAX_RATE

Snakecase: my_name, Pascalcase: MyName, camelCase:myName

Page 16: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University2.3 Variable , Constant, Objects and References

16

10/7/2021

Page 17: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Everything is Object

n Data is represented as objects.¨An object is essentially a memory block

that has specific values and supports specific types of operations.

n In Python 3, everything is object.¨Each object is identified by an identity, a

type, and a value.

17

10/7/2021

Page 18: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Objects in Python (1)n Identity is used to uniquely identify an object, usually

corresponding to the location of the object in computer memory. ¨ By the built-in id() function, we could obtain the unique id

identification of an object n Type is used to represent the Object’s data type (class).

Data type (class) is used to limit the value range of the object and the processing operations allowed to be performed. ¨ By the built-in type() function, we could determine the type of

an object.n Value is used to represent the value of the object.

¨ Use the built-in function print (obj1) to return the value of object obj1.

Page 19: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Objects in Python (2)

【Example 2.3】Using the built-in function type()、id() and print() to view object

【example 2.4】View Python built-in function objects.

>>> 123 #output:123>>> id(123) # output :140706558370656>>> type(123) # output :<class 'int'>>>> print(123) # output :123

>>> type(abs) # output :<class 'builtin_function_or_method'>>>> id(abs) # output :2529313427104>>> type(range) # output :<class 'type'>>>> id(range) # output :140706557885440

Page 20: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Variables: reference to objects(1)

n A python object is a block of memory data located in computer memory.

n In order to reference an object, an object has to be assigned to a variable through an assignment statement (also known as binding an object to a variable) .

n A reference to an object is a variable. A variable has to be initialized (binding to an object) before being used.

Page 21: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Variables: reference to objects(1)

【Example2.5】Use assignment statements to bind objects to variables.

>>> a = 1 # Literal expression 1 creates an int type instance object with a value of 1 and binds it to variable a >>> b = 2 >>> c = a + b # Expressions a+b create an int type instance object with a value of 3 and bind it to variable c

Page 22: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Variables: reference to objects (2)Python also supports the following assignment statements(1)chained assignment

(2)compound assignment statement

(3)series unpacking assignment

Page 23: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Variables: reference to objects (2)

【Example 2.6】Examples of assignment statements

>>> x = y =123 # Chain assignment,variables x and y both point to int object 123>>> i = 1 # Variable i points to int object 1>>> i += 1 # Conpound assignment,first evaluate the value of expression i+1, then create an int object with value 2 and bind it to variable I>>>a,b = 1,2 # Series unpacking assignment, variable a points to int object 1 and variable b points to int object 2>>> a,b = b,a # The values of two variables a and b are exchanged

Page 24: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

constant

n The python language does not support Symbolic constant (except literal constant), that is, there are no syntax rules that restrict changing the value of a Symbolic constant.

n Python language uses a convention to declare that variables that will not change during program operation are Symbolic constants. Generally, all uppercase letters are used to represent Symbolic constant.

【Example 2.7】Symbolic constant example

>>> TAX_RATE = 0.17 # Floating point type constant TAX_RATE>>> PI = 3.14 # Floating point type constant PI>>> ECNU = 'East China Normal University' # String constant ECNU

Page 25: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Object memory diagram (1)n When a python program is running, various objects (located

in heap memory) will be created in memory. Objects will be bound to variables (located in stack memory) through assignment statements, and objects will be referenced through variables for various operations.

n Multiple variables may reference the same object.n If an object is no longer referenced by variables in any

valid scope, the memory occupied by the object will be reclaimed through the automatic garbage collection mechanism.

Page 26: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Object memory diagram (2)

【Example 2.8】Example of variable incremental operation and corresponding object memory diagram

n The first statement creates an int object with a value of 100 and binds it to the variable i;

n The second statement first calculates the value of expression i+1, then creates an int object with value 101 and binds it to variable i.

>>> i = 100 >>> i = i+1

Page 27: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Object memory diagram (3)

【Example 2.9】An example of swap two variables and the corresponding object memory diagram.

>>> a = 123 #a points to an int type instance object with value of 123>>> b = 456 #b points to an int type instance object with value of 456>>> t = a # like a, t bind to the object instance 123>>> a = b #like b, a bind to the object instance 456>>> b = t #b bind to the object instance 123

series unpacking assignment -> swap 2 variable

Page 28: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Immutable objectn Once an immutable object is created, its value cannot be

modified, such as int, str, complex, etc.【Example 2.10】Immutable object example>>> a = 18 # Variable a binds to int object 18>>> id(a) # Output:140706365363776. Represents the id of the int object 18 referenced by a>>> a = 25 # Variable a binds to int object 25>>> id(a) # Output:140706365364000. >>> b = 25 # Variable b binds to int object 25>>> id(b) # Output:14070636536400. >>> id(25) # Output :140706365364000.

A variable is only a reference to an object. When a variable is reassigned, the old object is not changed, only a new one is created and bound to the variable.

Page 29: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Mutable object

n The value of a mutable object can be modified.¨ The variability of Python objects depends on the

design of their data types, that is, whether they are allowed to change their values

¨Most python objects are immutable object, but list, dict are mutable object

Page 30: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Mutable object【Example 2.11】Mutable object example

>>> x = y = [1, 2, 3] # The variables x and y bind to the list object [1, 2, 3]>>> id(x) # Output: 1656936944328. Represents the id of the list object [1, 2, 3] bound to by variable x>>> id(y) # Output: 1656936944328. Represents the id of the list object [1, 2, 3] bound to by variable y>>> x.append(4) # The list object [1, 2, 3] bound to by variable x is appended with an element 4>>> x # Output :[1, 2, 3, 4]. Indicates the list object [1, 2, 3, 4] bound to by variable x>>> id(x) # Output: 1656936944328. The ID of the list object [1, 2, 3, 4] bound to by variable x has not changed>>> x is y # Output :True. Indicates that variables x and y bind to the same list object [1, 2, 3, 4] >>> x == y # Output :True. Indicates that the list object values bound to by variables x and y are equal

Page 31: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Mutable object【Example 2.11】Mutable object example

>>> x = y = [1, 2, 3] # The variables x and y bind to the list object [1, 2, 3]>>> id(x) # Output: 1656936944328. Represents the id of the list object [1, 2, 3] bound to by variable x>>> id(y) # Output: 1656936944328. Represents the id of the list object [1, 2, 3] bound to by variable y>>> x.append(4) # The list object [1, 2, 3] bound to by variable x is appended with an element 4>>> z = [1, 2, 3, 4] # List object bound to by variable z [1, 2, 3, 4]>>> id(z) # Output :1656965757064. Represents the id of the list object [1, 2, 3, 4] bound to by the variable z>>> x is z # Output :False. Indicates that the variables x and z bind to different list objects [1, 2, 3, 4]>>> x == z # Output :True. Indicates that the list object values bound to by variables x and z are equal

Page 32: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University2.4 Data type

32

10/7/2021

Page 33: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

n In Python, every object has a type.n Python's data types is a set of value and operations defined

on the set. n including built-in data types, data types defined in modules,

and user-defined types.n Numeric data type :int、bool、float、complexn Sequence data type : Immutable (str、tuple、bytes)and

mutable (list、bytearray)n Collection data type :set、frozensetn Dictionary data type:dict. For example:{1: "one", 2: "two"}

Page 34: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Integer (1)

n Literal integer :

Page 35: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Integer (1)

【Example 2.12】Literal integer examples

>>> a=123>>> type(a)<class 'int'>>>> 1_000_000_000_000_000 1000000000000000>>> 0x_FF_FF_FF_FF4294967295

Page 36: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Integer (2)

n Python 3.8 supports the use of underscores as the thousandth mark of integers or floating-point numbers to enhance the readability of large values. Binary, octal and hexadecimal use underscores to distinguish 4-bit marks.

n Integer operation¨ Arithmetic operation, bit operation, built-in

function and mathematical operation function in math module.

Page 37: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Integer operation

Page 38: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Floating point (1)n Floating point constant 【Example 2.13】 Literal floating point example

>>> 3.14 # Output: 3.143.14>>> type(3.14) # Output :<class 'float'><class 'float'>

Page 39: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Floating point (2)n Operation of floating point number

¨ Arithmetic operation, function of floating-point operation in math module

Page 40: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Complex (1)n Create a complex object

【Example 2.14】Example of literal complex and complex object creation

>>> 1 + 2j # Output:(1+2j)>>> type(1+2j) # Output :<class 'complex’>>>> complex # Output :<class 'complex'>>>> c = complex(4, 5)>>> c # Output :(4+5j)>>>(4 + 5j)

Page 41: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Complex (1)n Complex object properties and methods

Properties / Methods

Explain Example

real R e a l p a r t o f complex number

>>> (1+2j).real #Result:1.0

imag Imaginary part of a complex number

>>> (1+2j).imag #Result:2.0

conjugate() Conjugate complex >>> (1+2j).conjugate() #Result:(1-2j)

Page 42: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Complex (2)n Operation of complex

Expression Result Explain1+2j (1+2j) complex digital area

quantity(1+2j) + (3+4j) (4+6j) addition(1+2j) - (3+4j) (-2-2j) subtraction(1+2j) * (3+4j) (-5+10j) multiplication(1+2j) / (3+4j) (0.44+0.08j) division(1+2j) ** 2.0 (-3+4j) power(1+2j) / 0.0 Runtime error Division. Divisor cannot

be 0cmath.sqrt(1+2j) (1.272019649514069+0.786

1513777574233j)Square root (call math module function)

cmath.sqrt(-2.0) 1.4142135623730951j Square root of complex number

Page 43: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Complex (2)【Example 2.15】Examples of complex operations

>>> a = 1 + 2j>>> b = complex(4, 5) # complex 4 + 5j>>> a + b # Complex addition. Output:(5+7j)(5+7j)>>> import cmath>>> cmath.sqrt(b) # Square root of complex number(2.280693341665298+1.096157889501519j)

Page 44: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Booleann The bool data type contains two values

¨ True or False【Example 2.16】 Literal boolean example

>>> True,False #Output:(True, False)(True, False)>>> type(True),type(False) #Output:(<class 'bool'>, <class 'bool'>)(<class 'bool'>, <class 'bool’>)>>> 1 + False>>> 1 + True

Page 45: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Booleann The bool data type contains two values

¨ True or False

【Example 2.17】Examples of bool object

>>> bool(0) #Output:FalseFalse>>> bool(1) #Output:TrueTrue>>> bool("abc") #Output:TrueTrue>>> bool("")>>> bool(" ")

Page 46: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University2.5 Operators and expressions

46

10/7/2021

Page 47: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Operatorn Operator is used to evaluate one or more operands in an

expression and return the result.n The order in which expressions are evaluated depends on

the combining order and priority of the operators.n parentheses "()" is used to force a change in the order of

operations.

【Example 2.18】Example of precedence of operators in expressions

>>> 11 + 22 * 3 # Output:7777>>> (11 + 22) *3 # Output:9999

Page 48: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Python operators and their precedence

From lowest to highest

Page 49: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Arithmetic operatorsPython operation Arithmetic

operatorsAlgebraic expression Python

expressionaddition + x + 7 x + 7subtraction - x - 5 x - 5Multiplication * b m or bm b * mExponentiation ** x ** yTrue division / x/y or or x/y

Floor division // x//yRemainder(modulo)

% x mod y x%y(also can be used with float)

49

10/7/2021

use the exponent ½ to calculate the square root :9 ** (1 / 2)

Page 50: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Operator Precedence RulesPython applies the operators in arithmetic expressions according to the following rules of operator precedence. These are generally the same as those in algebra:1. Expressions in parentheses evaluate first, so parentheses may force the order of evaluation to occur in any sequence you desire. Parentheses have the highest level of precedence. In expressions with nested parentheses, such as (a / (b-c)),the expression in the innermost parentheses (that is, b c) evaluates first.2. Exponentiation operations evaluate next. If an expression contains several exponentiation operations, Python applies them from right to left.

50

10/7/2021

Page 51: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Operator Precedence Rules3. Multiplication, division and modulus operations evaluate next. If an expression contains several multiplication, truedivision,floordivision and modulusoperations, Python applies them from left to right. Multiplication, division and modulus are “on the same level of precedence.”4. Addition and subtraction operations evaluate last. If an expression contains several addition and subtraction operations, Python applies them from left to right.Addition and subtraction also have the same level of precedence.3.

51

10/7/2021

Page 52: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Operator Precedence RulesFor the complete list of operators and their precedence (in lowest to highest order), see https://docs.python.org/3/reference/expressions.html#operator-precedence

52

10/7/2021

Page 53: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Operator groupingn When we say that Python applies certain operators

from left to right, we are referring to the operators’ grouping. For example, in the expression

a+b+cthe addition operators (+) group from left to right as if we parenthesized the expression as (a + b) + c. All Python operators of the same precedence group left to right except for the exponentiation operator (**), which groups right to left.

53

10/7/2021

Page 54: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Operator groupingn You can use redundant parentheses to group

subexpressions to make the expression clearer.y = a * x ** 2 + b * x + c

y = (a * (x ** 2)) + (b * x) + c

n Breaking a complex expression into a sequence of statements with shorter, simpler expressions also can promote clarity.

54

10/7/2021

Page 55: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Composition of expressions

n Operands, operators, parentheses,and function calling form expressions according to certain rules.

n The precedence of operators controls the calculation order of each operator

Page 56: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Expression example

【Example 2.18】Expression example

>>> import math # Import math module>>> a = 2 ; b = 10 #Variable a points to int object 2 and variable b points to int object 10

>>> a + b #Output:1212>>> math.pi #Output:3.1415926535897933.141592653589793>>> math.sin(math.pi/2) #Output:1.01.0

Page 57: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Mixed type expression and type conversionn implicit conversion.

¨ int, float, bool and complex objects can be mixed.¨ If the expression contains a complex object, the

other objects are automatically (implicitly) converted to a complex object and the result is a complex object.

¨ If the expression contains a float object, other objects are automatically (implicitly) converted to a float object and the result is a float object.

n Explicit conversion (cast)¨ Use target-type (value) to cast the expression to the

desired data type.

Page 58: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Type conversion example【Example 2.19】Implicit type conversion example

【Example 2.20】Explicit type conversion example

>>> f = 123 + 1.23>>> f #Output :124.23>>> type(f) #Output :<class 'float'>>>> 123 + True #True is converted to 1. Output:124>>> 123 + False #False is converted to 0. Output :123

>>> int(1.23) #Output :1>>> float(10) #Output :10.0>>> bool("abc") #Output:True>>> float("123xyz") #Report errors. ValueError: could not convert string to float: '123xyz’>>> x = 9999**9999; float(x) #OverflowError: int too large to convert to float

Page 59: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University2.6 Python statement

59

10/7/2021

Page 60: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

2.6 Python statement

n Statement is a process building block of Python program, which is used to define functions, define classes, create objects, assign variables, call functions, control branches, create loops, etc.

n Python statements are divided into simple statements and compound statements.

Page 61: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

2.6 Python statementn Simple statements include: expression statement,

assignment statement, assert statement, pass empty statement, del statement, return statement, yield statement, raise statement, break statement, continue statement, import statement, global statement, nonlocal statement, etc.

n Compound statements include: if statements, while statements, for statements, try statements, with statements, function definitions, class definitions, etc.

Page 62: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

【Example 2.1】 Calculate the area of a trianglen Given the three sides of a triangle, find the

area of the triangle (area.py). n Tips:assuming that the three sides are a, b

and c respectively, the area of the triangle is s= . Where h is half the circumference of the triangle

62

10/7/2021

)ch(*b)h(*)ah(*h

import math # Import statement to import math modulea = 3.0;b = 4.0;c = 5.0 #Assignment statement,bind variable to objecth = (a + b + c) / 2 #Expression statements = math.sqrt(h*(h-a)*(h-b)*(h-c)) #Call module math’s functionprint(s) # Built in function calling. Output the Area of triangle

Page 63: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Rules for writing Python statements(1)Use newline to separate. Generally, one statement per line.(2)Starting from the first column, there must be no spaces in front, otherwise a syntax error will occur. Note that comment statements can start anywhere; Compound statement constructs must be indented.

(3)Backslash ( \ ) is used when a code spans multiple lines. If the statement is too long, you can use a continuation character

(4) Semicolon ( ; ) is used to write multiple statements on one line.

>>> print(" If the statement is too long, you can use a continuation character (\),\to continue the line content .")

>>> a=0; b=0; c=0 # Variables a, b, and C all point to int object 0 >>> s="abc";print(s) # The variable s points to the str type instance object with the value “abc" and outputs abc

>>> print(" abc")>>> print(" abc") # Report errors.IndentationError: unexpected indent.

Page 64: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Compound statements and their indentation writing rules

n Compound statements (conditional statements, loop statements, function defin it ions , and c lass definitions, such as if、for、while、def、class, etc) are composed of header line and constructive sentence blocks (suites).

n A construction sentence block (suites) consists of one or more sentences

Page 65: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Compound statements and their indentation writing rules

(1) The header statement starts with the corresponding keyword (for example, if), and the construction block is one or more lines of indented code starting from the next line.

(2) Generally, indentation is to indent four spaces relative to the header statement, or any space, but the indented spaces of multiple statements in the same constructor code block must be aligned uniformly. If the statement is not indented, or the indents are inconsistent, it will lead to errors.(3) If the conditional statement, loop statement, function definition and class definition are short, they can be placed on the same line.

>>> for i in range(1,11): print(i, end=' ')...1 2 3 4 5 6 7 8 9 10

Page 66: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Python stylen The Style Guide for Python Code helps you write code

that conforms to Python’s coding conventions. total = x + yn The style guide recommends inserting one space on

each side of the assignment symbol = and binary operators like + to make programs more readable.

n https://www.python.org/dev/peps/pep0008/

66

10/7/2021

Page 67: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Comment statementn Start with the symbol "#" and end at the end of the line. Python

comment statements can appear anywhere. n The Python interpreter will ignore all comment statements, which

will not affect the execution results of the program.【Example 2.21】Example of comment statement

>>> #A "hello world!" program>>> # Comments can be anywhere, starting with “#” and ending at the end of the line>>> print("hello world") # Output:hello worldhello world

ctrl+1 in spyderctrl+4/5 block comment in spyderCtrl+/ in jupyter notebook in code cell

Page 68: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Empty statement pass

n Represents an empty code block

【Example 2.18】Empty statement example

>>> def do_nothing(): pass

Page 69: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University2.7 Functions and modules

69

10/7/2021

Page 70: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

what is function?n A function is a block of code that can be called repeatedlyn Function creation and call

n The parameters declared in function definition is formal parameters; when a function is called, the value provided for formal parameters is the actual parameters.

n The function can use “return” to return the value.

Page 71: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

self-define Function 【Example 2.23】Examples of declaring and calling functions(getLuckyNum.py)

import randomdef getLuckyNum(lim): # Create function object luck = random.choice(range(lim)) # Function body #luck = random.randrange(10,20) return luck #return result

l_num = getLuckyNum(10)print("your lucky number today is:",l_num)

Page 72: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

self-define Function

【Example 2.24】Declare and call function getValue (b,r,n) to calculate the final income v according to the principal b, annual interest rate r and number of years n.

def getValue(b,r,n): # Create function object getValue v = b*((1+r)**n) # Calculate final income v return v # Use return to return the valuetotal = getValue(1000,0.05,5) # Call the function getValueprint(total) # Print results

Page 73: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Built in functionn dir()、type()、id()、help()、len()、sum()、max()、min(),abs() ect.n The input function input () and the output function print () are

commonly called to interact with user.

【Example 2.25】Built in function usage example>>> s="To be or not to be, this is a question!">>> type(s) # Returns the data type to which the object s belongs. Output:<class 'str'>>>> len(s) # Returns the length of the string s. Output :39>>> s1 = [1,2,3,4,5]>>> max(s1) # Returns the maximum value of list s1. Output :5>>> min(s1) # Returns the minimum value of list s1. Output :1>>> sum(s1)/len(s1) # Returns the average value of the list s1. Output:3.0

Page 74: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Module functionn after module is imported, and functions in the module

cou ld be ca l l ed i n the form of “modu lename . functionname (arguments)”.

【Example 2.26】Example of module import 1

【Example 2.27】Example of module import 2

>>> import math>>> math.sin(2) #Output:0.90929742682568170.9092974268256817

>>> from math import sin>>> sin(2) #Output:0.90929742682568170.9092974268256817

Page 75: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

n How to use self defined function getValue and getLuckyNum?

75

10/7/2021

Page 76: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Function APIn Python language provides a large number of built-in functions,

standard library functions and third-party module functions.n The calling method of the function is determined by the

application programming interface (API).

Page 77: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

function calls in Pythonfunction call Return value explain

print('Hello') Output the string “hello” on the console Built in function

len('Hello') 5 Built in function

math.sin(1) 0.8414709848078965 Functions in math module

math.sqrt(-1.0) Runtime error Square root of negat i ve number

random.random() 0.3151503393010261

Funct i ons i n the r andom module. Note that different r a n d o m n u m b e r s a r e generated each time

Page 78: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University2.8 Output and input

78

10/7/2021

Page 79: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

FUNCTION PRINT AND AN INTRO TO SINGLE- ANDDOUBLE-QUOTED STRINGS

n The builtin print function displays its argument(s) as a line of text:

print(‘life is short’)n the argument ’life is short’ is a string—a sequence ofcharacters enclosed in single quotes (‘). You also may enclose a string in double quotes (").n Python programmers generally prefer single quotes.

When print completes its task, it positions the screen cursor at the beginning of the next line.

79

10/7/2021

【Example 2.28】Example of print>>>print(‘life is short’) #Output:life is shortlife is short

Page 80: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Printing a Comma-Separated List of Itemsn The print function can receive a comma separated list

of arguments, it displays each argument separated from the next by a space.

n Here we showed a comma separated list of strings, but the values can be of any type

80

10/7/2021

【Example 2.29】Example of print>>>print(‘life’,’is’,’short’); print(‘welcome’,2,’python’) life is shortWelcome 2 python

Page 81: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

escape character and escape sequencen When a backslash (\) appears in a string, it’s

known as the escape character. The backslash and the character immediately following it form an escape sequence. For example, \n represents the newline character escape sequence, which tells print to move the output cursor to the next line.

n Printing Many Lines of Text with One Statement

81

10/7/2021

【Example 2.30】Example of print many lines>>>print(‘life\nis\nshort’) life is short

Page 82: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Escape Sequences

Escape sequence Description\n Insert a newline character in a string. When the string

isdisplayed, for each newline, move the screen cursor to thebeginning of the next line.

\t Insert a horizontal tab. When the string is displayed, for each tab,move the screen cursor to the next tab stop.

\\ Insert a backslash character in a string\” Insert a double quote character in a string\’ Insert a single quote character in a string

82

10/7/2021

Page 83: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Ignoring a Line Break in a Long String

n You may also split a long string (or a long statement) over several lines by using the \ continuation character as the last character on a line to ignore the line break:

83

10/7/2021

【Example 2.31】Example of ignore a line break in a long string

>>> a = ‘this is a long string, \so we separate it in two lines’>>> print(a)#Output:this is a long string, so we separate it in two lines

Page 84: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

TRIPLE-QUOTED STRINGS

n Triple quoted strings begin and end with three double quotes (""") or three single quotes ('''). The Style Guide for Python Code recommends three double quotes (""")

n It is used to create:¨multiline strings,¨strings containing single or double quotes¨docstrings, which are the recommended

way to document the purposes of certain program components.

84

10/7/2021

Page 85: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Multiline Stringsn The following snippet assigns a multiline triple quotedstring to triple_quoted_string:

IPython knows that the string is incomplete because we did not type the closing ""“ before we pressed Enter. So, IPython displays a continuation prompt ... at whichyou can input the multiline string’s next line. This continues until you enter the ending""" and press Enter.

85

10/7/2021

>>> triple_quoted_string = """This is a triplequoted... string that spans two lines"""

>>> print(triple_quoted_string)#Output:this is a triplequoted string that spans two lines

Page 86: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

separate output with specific character

n separate output with comma and end with space

86

10/7/2021

>>> print(1, 2, 3, sep = ‘,’ , end = ‘ ’)#Output:1,2,3 >>>

Page 87: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

keep 2 decimal places in output

n 1.% Meta operator form¨ format string % (value1, value2) #compatible with python2, not recommended

87

10/7/2021

>>> ‘Result:%f' % 88 ’Result:88.000000'>>> ‘Name:%s, Age:%d, Weight :%3.2f' % (‘ZhangSan', 20, 53)‘Name:ZhangSan, Age:20, Weight:53.00'>>> '%(lang)s has %(num)03d quote types.' % {'lang':'Python', 'num': 2}'Python has 002 quote types.'>>> '%0*.*f' % (10, 5, 88)'0088.00000'

Page 88: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Format character

n %[(key)][flags][width][.precision][length]typen key is mapping keyn flags:

¨ ‘0’ :Fill with 0 on the left of the formatted result ¨ ‘-’: align to the left¨ ‘+’: a sign character, including: "+" (positive), "-"

(negative), ¨ ‘#’: uses another conversion

n width: minimum widthn length: decorate output, could be h,l or L

88

10/7/2021

Page 89: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Format character

n %[(key)][flags][width][.precision][length]typen type:

¨%d or %i :Signed integer(decimal)¨%o : Signed integer(octal)¨%x or %X Signed integer(hexadecimal), output

prefix ‘0x’ or ‘0X’ if flags is ‘#’¨%e or %E Scientific notation ¨%f or %F float number¨%c character¨%s string¨%% output %

89

10/7/2021

Page 90: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

keep 2 decimal places in output

n 2. Format built-in function¨ format(value) # equivalent to str(value)¨ format(value, format_spec) ¨ # equivalent to type(value).__format__(format_spec)

n The basic format of format specifier¨ [[fill]align][sign][#][0][width][,][.precision][type]

n fill (optional) is a fill character and can be any character except {};

n align is the alignment method, including: "<“ (left aligned), ">" (right aligned), "=" (padding between symbol and number, for example: '+000000120'), "^" (center aligned);

90

10/7/2021

Page 91: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

keep 2 decimal places in outputn 2. Format built-in functionn The basic format of format specifier

¨ [[fill]align][sign][#][0][width][,][.precision][type]n sign (optional) is a sign character, including: "+"

(positive), "-" (negative), “ " (positive with space, negative with -);

n '#' (optional) uses another conversion; n '0' (optional) the left side of the numeric format is

filled with zero; n width (optional) is the minimum width; n precision (optional) is precision; n type is a format type character.

91

10/7/2021

Page 92: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

2.Format built-in function

n type:¨ b : binary number¨ g : choose e or f format to output float number

based on its length¨ n : number, Use local thousands separator¨ _: use decimal thousandth separator or binary 4-

digit separator

92

10/7/2021

>>> format(81.2, "0.5f") #Output:'81.20000'>>> format(81.2, "%") #Output:'8120.000000%'>>> format(1000000, "_") #Output:1_000_000'>>> format(1024, "_b") #Output:'100_0000_0000'

Page 93: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

keep 2 decimal places in outputn 3. Format method of strings

¨ str.format(format string,value1,value2,…) #classmethod¨ format string.format(value1,value2,…) # object method¨ format string.format map(mapping)

n Syntax of format specifiers¨ {[index and key]:format_spec}¨ The optional index corresponds to the position of the

parameter value to be formatted, and the optional key corresponds to the key of the mapping to be formatted.

93

10/7/2021

Page 94: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

keep 2 decimal places in outputn 3. Format method of strings

¨ str.format(format string,value1,value2,…) #classmethod¨ format string.format(value1,value2,…) # object method¨ format string.format_map(mapping)

n Syntax of format specifiers¨ {[index or key]:format_spec}¨ The optional index corresponds to the position of the

parameter value to be formatted, and the optional key corresponds to the key of the mapping to be formatted.

94

10/7/2021

>>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(100)'int: 100; hex: 64; oct: 144; bin: 1100100'>>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(100)'int: 100; hex: 0x64; oct: 0o144; bin: 0b1100100'>>> '{2}, {1}, {0}'.format('a', 'b', 'c') 'c, b, a'>>> str.format_map('{name:s},{age:d},{weight:3.2f}',{'name':'Mary', 'age':20, 'weight':49})'Mary,20,49.00'

Page 95: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

keep 2 decimal places in outputn 4. use built-in function round(Round a number to a

given precision in decimal digits.) for example: round(math.pi,2)

95

10/7/2021

Page 96: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Multiline Stringsn Python stores multiline strings with embedded

newline characters. When we evaluate triple_quoted_string rather than printing it, IPython displays it in single quotes with a \n character where you pressed Enter

96

10/7/2021

>>> triple_quoted_string = """This is a triplequoted... string that spans two lines""">>> triple_quoted_string#Output:‘this is a triplequoted\nstring that spans two lines’

Page 97: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Including Quotes in Stringsn In a string delimited by single quotes, you may include

double quote characters:print('Display "hi” in quotes’)

print('Display \'hi\' in quotes’) #use the \" escape sequence

n A string delimited by double quotes may include single quote characters:

print("Display the name O'Brien")

print("Display \"hi\” in quotes") #use the \" escape sequence

n To avoid using \' and \" inside strings, you can enclose such strings in triple quotes:

print("""Display "hi” and 'bye' in quotes""")

97

10/7/2021

Page 98: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Printing the Value of an Expressionn Calculations can be performed in print statements:

98

10/7/2021

【Example 2.32】Example of printing the value of an expression

>>> a = 3; b = 7>>> print (‘a = ’, a, ‘b = ’, b, ‘ \n a + b = ’, a+b)#Output:a=3,b=7 a+b=10

Page 99: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

GETTING INPUT FROM THE USERn The builtin input function requests and obtains user input:

¨ input displays its string argument—a prompt—to tell the user what to type and waits for the user to respond. We typed Rong and pressed Enter. We use red text to distinguish the user’s input from the prompt text that input displays.

¨ Function input then returns those characters as a string that the program can use.Here we assigned that string to the variable name.

99

10/7/2021

>>> name = input(“what’s your name?”)#Output:what’s your name? Rong>>> name#Output:’Rong’>>> print (name)#Output:Rong

Page 100: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

n Evaluating name displays its value in single quotes as‘Rong' because it’s a string. Printing name displays the string without the quotes. If you enter quotes, they’re part of the string.

100

10/7/2021

>>> name = input(“what’s your name?”)#Output:what’s your name? ’Rong’>>> name#Output:”’Rong’”>>> print (name)#Output:’Rong’

Page 101: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Function input Always Returns a Stringn Consider what’s the output of following snippets after

user inputted 8 and 4

n Python “adds” the string values ‘8' and ‘4', producing the string ‘84'. This is known as string concatenation. It creates a new string containing the left operand’s value followed by the right operand’s value.

101

10/7/2021

value1 = input(‘Enter the first number:’)value2 = input(‘Enter the second number:’)print(value1,’ + ’,value2, ‘ = ’, value1 + value2)

Page 102: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Getting an Integer from the Usern If you need an integer, convert the string to an

integer using the builtin int function:

102

10/7/2021

Page 103: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

convert value to an integern convert a floating point value to an integer

n convert a bool value to an integer

n convert a complex to an integer

103

10/7/2021

Page 104: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

trigger errorn If the string passed to int cannot be converted to an

integer, what will happen?

104

10/7/2021

Page 105: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Getting data from the Usern To convert strings to floating point numbers, use the

builtin float function.n To convert strings to complex numbers, use the

builtin complex function

105

10/7/2021

Page 106: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Try built-in function eval(Evaluate the given source)

a = eval(input(‘please input something, I will tell you its type’))print(‘type is’, type(a))

106

10/7/2021

Page 107: Chapter 2 Fundamentals of Python

Zhou Rong

Control & Computer Engineering School

North China Electric Power University

Wrap up

107

10/7/2021