Upload
others
View
36
Download
0
Embed Size (px)
Citation preview
Chapter 1 Introduction to Python Programming
Zhou [email protected]
North China Electric Power UniversityControl & Computer Engineering School
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
2
9/23/2021
Outline
1.1 Computer & Programming language
1.2 Introduction to Python
1.3 Python language version and development
environment
1.4 Develop and run Python programs
1.5 Packaging and distribution of programs
1.6 Online help and related resources
Zhou Rong
Control & Computer Engineering School
North China Electric Power University1.1 Computer & Programming language
3
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
4
9/23/2021
History of computer
n What is computer:
¨ An electronic device that can store programs
and data, execute programs automatically, and
process various digital information quickly and
efficiently.
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
5
9/23/2021
History of computer
n Father of computer:
¨ Alan Mathison Turing : Can Machines Think?
¨ John von Neumann pioneered game theory and,
along with Alan Turing and Claude Shannon, was
one of the conceptual inventors of the stored-
program digital computer
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
6
9/23/2021
History of computer
n Stored-program computer, a computer that
stores instructions in binary-number format in
its memory to enable it to perform a variety of
tasks in sequence or intermittently. The idea was
introduced in the late 1940s by John von
Neumann
EDVAC
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
7
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
5 Units
n Arithmetic unit: Responsible for completing all arithmetic operations and logical operations tasks
n Control unit: Control the work of all parts of the entire computer. The controller controls all the actions of the computer hardware system.
n Memory unit: stores instructions in binary-number format ¨ 8 bits is called a byte , each byte has a unique
address§ 1KB=1024B=210
§ 1MB=1024KB=220
§ 1GB=1024MB=230 § 1TB=1024GB=240
§ 1PB=1024TB=250
8
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
5 Units
n Input device: to accept user input (Raw data and programs )
n Output device: to convert the calculation results into a form acceptable to people and output to the corresponding medium (for example: monitor).
9
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
Memory
10
9/23/2021
Adress Data
Bit
Byte
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
Computer systemn A computer system consists of hardware and software
¨ Physical computers and peripherals are collectively referred to as hardware
¨ The programs that computers execute are part of software(=program + data + documents)
n Software is generally divided into two categories: system software and application software
11
9/23/2021
user userApplication SoftwareSystem Software
operating system
computer
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
Programming Language
n A programming language, is a set of grammatical rules used to define computer programs. Each language has a unique set of syntax and program instructions
n Programming languages are divided into low-level languages and high-level languages¨ Low-level languages are machine-specific¨High-level languages are machine independent
12
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
Programming Language
n Machine language and assembly language are low-level languages
n Machine language is the first generation of programming language, using binary code to write programs, readability is poor, but can be directly recognized and executed by computers
n Assembly language is a second generation programming language that uses simple mnemonics to express instructions
13
9/23/2021
Machine language program0 0 1 0 0 0 1 11 1 1 0 1 1 0 10 1 1 0 0 0 0 10 1 1 1 0 1 1 0
assembly language program
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
Programming Language
n A high-level language is a language independent of computer architecture. Its biggest feature is that it describes the process of problem processing in a form similar to natural language ¨C、C++、C#、Java and Python
14
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
Classification of Programming Languages
n Procedural oriented programming language¨FORTRAN、COBOL、Basic、Ada、Pascal、
Cn Object-oriented programming language¨Java、C#、C++、Smalltalk、Visual Basic
n Functional programming languages ¨Lisp、Scheme、Haskell、F#
n Logical programming language :Prologn Python is a multiparadigm programming
language 15
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
Computational Thinking and Programming Methods
n In the process of understanding and transforming the world, human beings have formed the following three basic thinking ¨ Logical thinking: characterized by reasoning and
deduction, represented by mathematics ¨ Experimental thinking: characterized by
experiment and verification, represented by physics
¨ Computational thinking: characterized by design and construction, represented by computer science
16
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
The essence of computational thinking
n The essence of computational thinking is abstraction and automation
n Program design method belongs to the category of computational thinking, common program design method mainly includes two kinds ¨ Structured programming and object-oriented
programming ¨ Structured programming usually adopts the top-
down, stepwise refinement method of programming
17
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
The basic idea of top-down programming
n Problem decomposition, algorithm implementation, combination program
n A program designed from the top-down method is generally implemented through the bottom-up method ¨ Implementing, running, and testing each of the
basic functions, and then testing the overall function that consists of the basic functions, can help locate errors
18
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
Source file
n After you write a program in a text editor, save the file. The file that contains the program code is called source file.
19
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
Program Execution
n There are two ways to convert a source file into a machine language
¨ Compiler: The Compiler translates source code into the target language
¨ Explanation: The interpreter interprets and executes high-level programming languages directly
20
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
Classify High-Level Programming Languages by Their Execution Mechanismn Static languages and scripting languages
¨ The language executed in a compiled manner is a static language, such as C, C++, C#, Java,etc.
¨ Advantage : the compiled object code can be run directly; The object code produced by compilation is usually faster to execute
n The language executed in an interpreted manner are scripting languages, such as JavaScript, PHP, Python,etc. ¨ Advantage : the source code can be run in any
operating system interpreter, portability; Interpretative execution requires the preservation of source code, so program error correction and maintenance are very convenient 21
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University1.2 Introduction to Python
22
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
About Python
n Life is short, you need Python
23
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
Welcome to Python -the world’s most popularn Welcome to Python—one of the world’s most widely
used computer programming languages and, according to the Popularity of Programming Languages (PYPL) Index, the world’s most popular
n https://pypl.github.io/PYPL.html
24
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
Pythonn Is an interpreted, object - oriented programming
languagen Is an open source language with a large number of
libraries that allow you to efficiently develop a variety of applications
n Python language features¨ Simple, advanced, object oriented, extensible, free
open source, portability, rich library, embeddable n The scope of Python
¨Operating system management, scientific computing (NumPy, SciPy, Pandas, SymPy, Matplotlib, OpenCV, VTK, ITK),Web applications(Django、Flask、Pyramid, etc),GUI, development(Tkinter、wxPython or PyQt libraries)、others (game development, etc.) 25
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
1.3 Python Language Version and Development Environment
26
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
n Two major releases: Python 2 and Python 3n Python 3 was not designed with backward
compatibility in mind n Python language implementation: The Python
interpreter n Common Python implementations:
¨ Cpython, Jython, IronPython, PyPyn An integrated development environment for Python
¨ IDLE(built-in), Spyder, PyCharm, Eclipse + Pydevbuilt-in, Visual Studio + Python Tools for Visual Studio, PythonWin
27
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
Let’s Do it
n Our IDE (Integrated Development Environment)
28
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
Install anaconda
n We use the easy-to-install Anaconda Python distribution. It comes with almost everything you’ll need to work with our examples, including:¨ the IPython interpreter,¨most of the Python and data science libraries we
use,¨ a local Jupyter Notebooks server so you can load
and execute our notebooks, and¨ various other software packages, such as the
Spyder Integrated Development Environment (IDE)—we use only IPython and Jupyter Notebooks in this book.
29
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
n Download the Python 3.x Anaconda installer for Windows, macOS or Linux from:n https://www.anaconda.com/download/
n When the download completes, run the installer and follow the onscreen instructions.
n To ensure that Anaconda runs correctly, do not move its files after you install it.
30
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University1.4 Develop and Run Python Programs
31
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
n There are generally two ways to develop and run Python programs ¨ Interactive mode: In command line window, type
“ipython”, press Enter,open ipython interpret, then enter small bits of Python code called snippets and immediately see their results.
¨ Interactivity is generally useful for debugging small amounts of code(snippets)
¨ Script mode: To write Python programs and save them in one or more source files(has the .py extension), which are then compiled and executed by the Python interpreter. This mode is suitable for the development of more complex applications
32
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
Interpret and Execute Python Programs n Interactive Example(open the Anaconda Command Prompt)
¨Output Hello world!¨ Use the Python interpreter for mathematical
operations >>> 1.1+2.2+3.3+4.4+5.5 #output:16.5>>> (1+0.01)**365
¨ running multiple expressions at the same time: running multiple expressions separated by commas at the same time returns tuples >>> 2,2**10 #output:(2, 1024)
¨ Close the iPython interpreter Ctrl+d ;Or enter exit + Entercommand;Or close the command line window 33
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
Interpret and Execute Python Programs n File format Example
¨Output ‘Good!’ 5 times print('Good!'*5)
¨ execute multiple lines of code(print numbers in the range of 0 to 9, with a space as the separator) for x in range(10): print(x, end=' ')
34
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
Write and Execute Python Source File Programsn Write Python programs as text files( .py )n The process of writing Python source code files and
executing the program through the Python compiler/interpreter
35
9/23/2021
with extension:“.pyc”
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
n Example : get your today’s lucky numberimport random # Import library modules print("Hello, world") #output:Hello, Worldprint("Your lucky random number today is:", random.choice(range(10))) #output a number randomly selected from 0 to 9 input() #wait for user input
36
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
Executing a Python Program Using the IPython Interpreter- Law of large numbersn execute a script named RollDieDynamic.py(simulates
rolling a six-sided die, It presents a colorful animated visualization that dynamically graphs the frequencies of each die face)
n Changing to Examples Foldern Executing the Script: ipython RollDieDynamic.py 6000
1(The numbers 6000 and 1 tell this script the number of times to roll dice and how many dice to roll each time)
37
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
38
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
Problems That May Occur at Execution Time
n Programs often do not work on the first try. For example, an executing program might try to divide by zero (an illegal operation in Python). This would cause the program to display an error message. If this occurred in a script, you’d return to the editor, make the necessary corrections and re-execute the script to determine whether the corrections fixed the problem(s).
n they’re called runtime errors or execution-time errors. Fatal runtime errors cause programs to terminate immediately without having successfully performed their jobs. Non-fatal runtime errors allow programs to run to completion, often producing incorrect results
39
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
Writing and Executing Code in a Jupyter Notebook
n Jupyter Notebook—an interactive, browserbased environment in which you can write and execute code and intermix the code with text, images and video.
n Jupyter Notebook is similar to working with IPython—in fact,Jupyter Notebooks use IPython by default
n Point your fold as Jupyter notebook default fold:¨ Find out file named“jupyter_notebook_config.py”
by command “jupyter notebook –-generate-config”¨ add “c.NotebookApp.notebook_dir = ‘you fold path’”
in file “jupyter_notebook_config.py”
40
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
JupyterLab interface
n enables you to manage your notebook files and other files that your notebooks use (like images and videos)
n JupyterLab also makes it convenient to write code, execute it, see the results, modify the code and execute it again.
n Open Jupyter lab in Browser¨ Anaconda Command Prompt-type in
command:jupyter lab¨ reopen JupyterLab by entering the following
address in your web browser: http://localhost:8888/lab
41
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
42
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
n Creating a New Jupyter Notebookn Renaming the Notebook
n To the cell’s left, the notation [ ]: is where the Jupyter Notebook will display the cell’s snippet number after you execute the cell
43
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
n To execute the current cell’s code, type Ctrl + Enter (or control + Enter).
n JupyterLab executes the code in IPython, then displays the results below the cell:
n Adding and Executing Another Cell(Shift + Enter)n Jupyter notebook enables you to work through them
snippet by snippet and see the outputs appear as you execute each snippet 44
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
Closing JupyterLab
n When you’re done with JupyterLab, you can close its browser tab, then in the Terminal, shell or Anaconda Command Prompt from which you launched JupyterLab, type Ctrl + c (or control + c) twice.
n Jupyter team’s introduction to JupyterLab at:https://jupyterlab.readthedocs.io/en/stable/index.html
45
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University1.5 Package and Release Programs
46
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
n The process of packaging Python source code into executable files to run Python programs directly on operating systems where the Python interpreter is not installed is called "program distribution."
n The most common way to package and release Python programs is the third-party extension package PyInstaller
47
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
n Install the PyInstaller package: pip install pyinstaller¨ Generating executable programs with PyInstaller:
PyInstaller option Python source file ¨ PyInstaller supports the following common options
n -h or--help:view help informationn -F or--onefile:generates a single executable file n -D or--onedir:generates a directory containing
the executable file and associated supporting files and subdirectories
n --clean:cleans the PyInstaller cache and removes temporary files from the packaging and publishing process
n Use PyInstaller to generate an executable file: pyinstaller -F hello2.py
48
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University1.6 Online Help and Related Resources
49
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
n Python interactive help system¨ Enter the interactive help system by typing the help()
function directly ¨ Type Help (object) to get help information about the
object¨ Example of using the Interactive Help system in
Python (1)Enter the interactive help system. Type help() and press Enter(2)Display all installed modules. Type modules and press Enter(3)Display modules related to Random. Type modules random and press Enter(4)Display the help information of module Random. Type random and press Enter(5)Display information about the random function of the Random module. Type random.random and press Enter
(6)Exit the help system. Type quit and press Enter50
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
n Python interactive help system¨ Use Python's built-in functions to get help
information (1) View the list of Python built-in objects. Enter the command: >>> dir(__builtins__)(2)View the information about float. Enter the command >>> float (3)See the help information for the built-in class float
51
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
Online Help and Related Resources
n PYTHON DOCUMENTATIONn The Python Language Reference:
¨ https://docs.python.org/3/reference/index.htmln The Python Standard Library:
¨ https://docs.python.org/3/library/index.htmln Python documentation list:
¨ https://docs.python.org/3/
52
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
GETTING YOUR QUESTIONS ANSWERED
n Popular Python and general programming online forums include:
n pythonforum.ion https://www.dreamincode.net/forums/forum/29pyth
on/n StackOverflow.com
53
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
GETTING JUPYTER HELPn Jupyter Notebooks support is provided through:
¨ Project Jupyter Google Group:n https://groups.google.com/forum/#!forum/jupyter
¨ Jupyter realtime chat room:n https://gitter.im/jupyter/jupyter
¨ GitHubn https://github.com/jupyter/help
¨ StackOverflow:n https://stackoverflow.com/questions/tagged/jupyter
¨ Jupyter for Education Google Group (for instructors teaching with Jupyter):n https://groups.google.com/forum/#!forum/jupyter-
education 54
9/23/2021
Zhou Rong
Control & Computer Engineering School
North China Electric Power University
wrap up
55
9/23/2021