<jupyter_start><jupyter_text>Introduction to Python  Python is the popular programming language, and it's especially great for beginners.With Python, you can build apps for the web, desktop, and command line. Python is one of the best-suited languages for working with data science and Artificial Intelligence (AI), and it's also used to program IoT devices, microcontrollers, and more!Since its introduction by <NAME> in 1990, it has undergone many changes. * **Python 2.0 in 2000**. * **Python 3.0 in 2008**: This version of Python cleaned up many of the inconsistencies in the design of the various releases of Python 2 (often referred to as Python 2.x). However, it was not backward compatible. That meant that most programs written for earlier versions of Python could not be run using implementations of Python 3.0. We use Python 3 throughout this course.**Officeal Web Site**: https://www.python.org/  1 The Python programming languagePython is a `high-level language`;Two kinds of programs process high-level languages into low-level languages: **compilers and interpreters**People often describe programming languages as either **compiled** or **interpreted.*** **Compiled**: programs are translated into machine language and then executed by hardware; * **Interpreted**: programs are read and executed by a software interpreter.Usually `C/C++` is considered a compiled language.`Python` is considered an interpreted language. But the distinction is not always clear-cut.There are some general differences between compiled and interpreted languages.   1.1 The compiled  ,statically typed language : C/C++ **The compiled language** https://en.wikipedia.org/wiki/Compiled_language>A compiled language is a programming language whose implementations are typically  compilers(编译器) :translators that generate **machine code** from `source code`A compiler reads the program and translates it completely before the program starts running. * **compiling**: source code is compiled to object code(translate source code from a high-level programming language to machine code)* **linking**: object code is linked to executable file(combines one or more object files into a single executable file)you can **execute** the `executable` file repeatedly without further translation. ![compile](./img/compile.png) **The statically typed language**In a statically-typed language,you can tell by looking at the program what type each variable refers to.In general, **static** refers to things that happen at **compile** time (while a program is being compiled),For example, in C/C++ you can write a program like this:<jupyter_code>%%file ./demo/src/cpp_styped.cpp
#include <iostream>
using namespace std;
 
int main()
{

   int a=1;
   float b=0.1;
   string c="Southeast University";
   cout <<a<<endl; 
   cout <<b<<endl; 
   cout <<c<<endl; 
   return 0;
}<jupyter_output><empty_output><jupyter_text>The begin three lines of the program includes type declarations for the variables:`a,b and c`are declared to be integer,float and string, which means can `check` at `compile time` whether the addition operator is legal for this type (it is). The return value is also declared to be an integer.Because of these declarations, the compiler can check whether the values provided have the right type.These checks happen before the program starts executing, so `errors` can be found `earlier`. More importantly, errors can be found in parts of the program that have never run. Furthermore, these checks don’t have to happen at run time, which is one of the reasons compiled languages generally run `faster` than interpreted languages **1 Compiling source code to the object code(machine coce)**<jupyter_code>!g++ -c -o ./demo/obj/cpp_styped.o ./demo/src/cpp_styped.cpp<jupyter_output><empty_output><jupyter_text>* -c compiling source code to object code* -o output to the file<jupyter_code>!dir .\demo\obj\cpp_styped.o<jupyter_output><empty_output><jupyter_text>**2 Linking the object code to executable file(combines one or more object files into a single executable file)**<jupyter_code>!g++ -o ./demo/bin/cpp_styped ./demo/obj/cpp_styped.o
!dir .\demo\bin\cpp_styped.exe
!.\demo\bin\cpp_styped<jupyter_output><empty_output><jupyter_text>1.2 Special commands in the code cell of jupyter notebook* magic* shell 1.2.1  `magic` functionsThe magic function system provides a series of functions which allow you to control the behavior of IPython itself, plus a lot of system-typefeatures. There are two kinds of magics,* cell-oriented: %%* line-oriented: %    1.2.1.1  Cell magics: `%%`https://ipython.readthedocs.io/en/stable/interactive/magics.htmlCell magics are prefixed with a double `%%`, and they are functions that get as an argument not only the rest of the line, but also `the lines below it in a separate argument`.```bash%%file filename```Write the contents of the **CELL** to a file.  1.2.1.2  Line magics: `%`Line magicsare prefixed with the `%` character and work much like OS command-line calls: they get as an argument the rest of the line, where arguments are passed without parentheses or quotes.<jupyter_code>%ldir<jupyter_output>������ J �еľ��� cmh
 �������к��� 9C25-3306

 j:\SEU\SEECW\SE\SEES\notebook ��Ŀ¼

2022/05/24  15:28    <DIR>          .
2022/05/24  15:28    <DIR>          ..
2022/05/24  13:54    <DIR>          .ipynb_checkpoints
2022/02/02  12:00    <DIR>          code
2022/05/21  22:01    <DIR>          coolpropdemo
2022/02/02  13:42    <DIR>          data
2022/05/17  15:22    <DIR>          demo
2022/05/23  14:40    <DIR>          gtest_windows
2022/02/10  12:26    <DIR>          img
2021/12/15  20:23    <DIR>          mymath
               0 ���ļ�              0 �ֽ�
              10 ��Ŀ¼ 94,131,228,672 �����ֽ�<jupyter_text>**Below is a list of available magics**<jupyter_code>%lsmagic<jupyter_output><empty_output><jupyter_text>1.2.2  Shell command Run the `system command` in the cell```bash!command```![pythonversion](./img/pythonversion.jpg)<jupyter_code>!python --version<jupyter_output><empty_output><jupyter_text>1.3 Python: the interpreted ,scripting, dynamically typed language  An interpreted languagehttps://en.wikipedia.org/wiki/Interpreted_language**An interpreted language** is a type of programming language for which most of its implementations execute instructions directly and freely, without previously compiling a program into machine-language instructions. The **interpreter executes** the program **directly**, translating each statement into a sequence of one or more subroutines, and then into another language (often machine code).An interpreter reads a high-level program and executes it, meaning that it does what the program says. It processes the program a little at a time, alternately reading lines and performing computations. ![interpret](./img/interpret.png)Python is considered an interpreted language because Python programs are executed by an interpreter. There are two ways to use the interpreter: * `command-line` mode: interpreter the statement in the Python Shell* `script` mode:  running a program in a file     Python Script You can write `a program in a file` and use the interpreter to execute the contents of the file.Files that contain Python programs have names that end with  .py. Such a file is called a script(脚本).Python is the scripting language* A Python program is a sequence of `definitions and commands`<jupyter_code>%%file ./code/python/demo.py
a=2
b=3
c=6
print('The Sample Script')
print('a*b+c=',a*b+c)<jupyter_output><empty_output><jupyter_text>To execute the program, we have to tell the interpreter the name of the script:<jupyter_code>!python ./code/python/demo.py<jupyter_output><empty_output><jupyter_text>The dynamically typed language https://en.wikipedia.org/wiki/Type_systemDynamic_type_checking_and_runtime_type_information>Dynamic type checking is the process of verifying the type safety of a program at runtimeIn a dynamically-typed language, you `don’t always know the type `of a variable until the program is **running.**In general, dynamic refers to things that happen at **run** time (while a program is running).For example,<jupyter_code>a = 1233
print(a + 11)
a = 0.12222
print(a + 0.023)
a = "Southeast University"
print(a + ", Naning")<jupyter_output><empty_output><jupyter_text>Looking at this code,the variable `a` to be set to the value 1, then to the value `0.1`, then to a string `"Southeast University"`.The variable `a` is assigned several times,each time with values with `different` types. Any values that support the addition operator will work;   Output: print() function<jupyter_code>b = 1
print("b = ", b)
print("2*3.2 =", 2 * 3.2)<jupyter_output><empty_output><jupyter_text>Multiple Assignment Python allows multiple assignment.<jupyter_code>x, y, z = 2, 3, 10
x
y
z
# use multiple assignment to swap the bindings of two variables.
x, y = y, x
print('x =', x)
print('y =', y)<jupyter_output><empty_output><jupyter_text>Comments: `` Comments are any text to the right of the  symbol and is mainly useful as notes for the reader of the program. Text following the symbol   is not interpreted by Python. It is one good way to enhance the readability of code>The comment in C/C++>* `block comments` begin with /* and end with */>* `line comments`  begin with `//` and end with the next `newline` character  1.5 Variable    Variable NameIn Python, `variable names` can contain * uppercase and lowercase `letters, digits`* they `cannot start with a digit` * the special character _* **reserved words** (sometimes called keywords) in Python that have built-in meanings and `cannot be used` as variable names.Python variable names are case-sensitive* e.g., `Julie and julie` are different names.Apt choice of `variable names` plays an important role in enhancing readability.  2 The Basic Elements of Python  2.1 Numerical Types Python has **four** basic types:* **int**  integers: -3 or 5 or 10002* **float** real numbers： 3.0 or 3.17 or -28.72，scientific notation： 1.6E3* **bool** the Boolean values True and False* None is a type with a single value.  * `None` is just a value that commonly is used to signify `empty`, or `no value here`.The built-in Python function type can be used to find out the type of an object:<jupyter_code>type(3)
type(3.0)
type(True)
type(TRue) # True Only!
f=False  # False Only!
f
Var1=None 
type(Var1)
type(NONE) # None Only!!<jupyter_output><empty_output><jupyter_text>2.2 Arithmetic Operators**Operators** on types *int and float*```python   +   Addition   -   Subtraction   *   Multiplication   /   Float Division,Returns a float   //  Integer Divisio, Returns the floor integer   %   Modulus (Remainder)   **  Exponentiation```  `Float` division Returns a float<jupyter_code>6/2<jupyter_output><empty_output><jupyter_text>`Integer` division **the floor integer*** returns the floor integer（向下取整) the quotient and ignores the remainder）<jupyter_code>6//2 
7//2<jupyter_output><empty_output><jupyter_text>Modulus (Remainder)<jupyter_code>7%2<jupyter_output><empty_output><jupyter_text>Exponentiation$i**j$ is $i$ raised to the power $j$,that is * $i^j$ If $i$ and $j$ are both of type int, the result is an int.<jupyter_code>2**3<jupyter_output><empty_output><jupyter_text>If either of them is a float, the result is a float<jupyter_code>2.1**3   
2**3.1<jupyter_output><empty_output><jupyter_text>Compound Assignment OperatorsEach of the arithmetic operators has a corresponding shorthand assignment counterpart,```python +=, -=, *=, /=, //=, **=, %=```For example i += 1 is the same as i = i + 1.<jupyter_code>a=3
a+=1
a<jupyter_output><empty_output><jupyter_text>2.3 Relational OperatorsThe **Relational(comparison) operators** are:```python   ==  equal   !=  not equal   >   greater   >=  at least   <   less   <=  at most```<jupyter_code>1==2
1<=2<jupyter_output><empty_output><jupyter_text>2.4 Logical Operators ```python  and, or, not```The operators on type bool are:    ```python  a and b    True if both a and b are True, and False otherwise.  a or  b    True if at least one of a or b is True, and False otherwise.  not   a    True if a is False, and False if a is True.```<jupyter_code>2>1 and 3>2
1>2 or 3>2
not 1>2<jupyter_output><empty_output><jupyter_text>Further Reading* [Built-in Types:Numeric Types — int, float, complex](https://docs.python.org/3/library/stdtypes.htmlnumeric-types-int-float-complex)  * **complex numbers**  3 Strings Objects of type `str` are used to represent strings of characters.String literals are written in a variety of ways:* **Single quotes**: 'abc'(allows embedded double quotes)* **Double quotes**: "abc"(allows embedded single quotes).* **Triple quoted**: '''abc''' or  """abc""",(allows `multi-lines`)Triple quoted strings may **span multiple lines** - all associated whitespace will be included in the string literal.<jupyter_code>'a '
type('a')
type("abc")
dstr="abc'abc'"
print(dstr)
a="""
     School Of Power Engineeing
     Southeast Unicersity
     Nanjing,China
     
     Triple quoted
"""
a
print(a)
3*4   # The operator *
3*"abc"   # The operator * is overloaded
# 3*4 is equivalent to 4+4+4, 
# the expression 3*'a' is equivalent to 'a'+'a'+'a'.
3+4 # The operator *
'a'+'b1'  # The operator * is overloaded
'a'*'a'<jupyter_output><empty_output><jupyter_text>The type checking in Python is not as, strong as in some other programming languages (e.g., Java).<jupyter_code>'4' < 3  # all numeric values should be less than all values of type str :Python2, not python3!<jupyter_output><empty_output><jupyter_text>**Strings are one of several sequence types in Python** They share the following operations with `all sequence` types* the length of a string: using the `len(str)` function. * Indexing can be used to extract individual characters from a string.    * all indexing is **zero-based*** Slicing(分片） is used to extract `substrings` of arbitrary length.    * **s[i:j]** :the substring between `i`  to j-1. **NOT j**<jupyter_code># the len(str) function. 
len('abcd')
# all indexing is zero-based
'abcd'[0]
str1='abcd'
str1[0]
# all indexing is zero-based
'abcd'[1]
# the substring i to j-1 
'abcd'[1:3]
'abcd'[3]<jupyter_output><empty_output><jupyter_text>3.1 Strings are `immutable`(不可变类型)The `String` **cannot be modified `after they are created`**.If you try to modify a character in a string,<jupyter_code>greeting = 'Hello, world!'# string greeting 
greeting[0] = 'J' # try to modify the greeting 
greeting[0]<jupyter_output><empty_output><jupyter_text>You get an **error**```TypeError: 'str' object does not support item assignment ``` The reason for the error is that `strings are immutable`, which means * you can’t **change** an existing string The best you can do is `create a new string` that is a variation on the original:<jupyter_code>new_greeting = 'J' + greeting[1:]
new_greeting<jupyter_output><empty_output><jupyter_text>This example `concatenates(+)` new first letter onto a slice of greeting. It has no effect on the original string.  3.2 Advanced String Slicing 3.2.1 Omit the starting/ending indexyou can slice a string with a call such as s[i:j], which gives you a portion of string s from index i to index j-1. However this is not the only way to slice a string! * omit the starting index, start the slice at index 0. * omit the ending index, end the slice at the end of the string.<jupyter_code>s = 'Python is Fun!'
s[1:5]
# the omitted starting index is 0,
s[:5]
# the omitted ending index, end the slice at the end of the string.is 0,
s[1:]<jupyter_output><empty_output><jupyter_text>**original string**  If you `omit` both the `start and ending` index, you get your contents of `original string`! - new string<jupyter_code># get the original string
s[:]<jupyter_output><empty_output><jupyter_text>3.2.2 The slicing stepYou can add a third parameter, k, ```pythons[i:j:k]```This gives a slice of the string s from index i to index j-1, with step size k. Check out the following examples:<jupyter_code>s = 'Python is Fun!'
s[1:12:2]
s[1:12:3]<jupyter_output><empty_output><jupyter_text>**every `other` character**step=2With ```s[::2]```, we're asking for the `full string s` (from index 0 through 13), with a `step size of 2`, so we end up with every **other** character> in s<jupyter_code>s[:]
s[::2]<jupyter_output><empty_output><jupyter_text>**reversing a string** step=-1 * the negative step<jupyter_code>s = 'Python is Fun!'
s[::-1]  #  the negative step<jupyter_output><empty_output><jupyter_text>3.2.3 positive and negative indexsSee the Figure for a helpful illustration of slicing with `positive and negative` integers.![slicing](./img/Python-Slicing.jpg)<jupyter_code>s='HELLO!'
s[2:4]
s[-5:-2]
s[:-1]
s[:]
s[1:5:2]<jupyter_output><empty_output><jupyter_text>**Please try the slicing in the follow cell**        Operator    Usage    Description    Examples s = 'Hello'            [i]      [-i]    str[i]      str[-i]    Indexing to get a character.    The front index begins at 0; back index begins at -1 (=len(str)-1).    s[1] ⇒ 'e'    s[-4] ⇒ 'e'        [m:n:step]    [m:n]      [m:]      [:n]      [:]        str[m:n:step]      str[m:n]      str[m:]      str[:n]      str[:]    Slicing to get a substring.From index m (included) to n (excluded) with step size.    The defaults are: m=0, n=-1, step=1.    s[1:3] ⇒ 'el's[1:-2] ⇒ 'el's[3:] ⇒ 'lo's[:-2] ⇒ 'Hel's[:] ⇒ 'Hello's[0:5:2] ⇒ 'Hlo'<jupyter_code>s='Hello'
s[1]<jupyter_output><empty_output><jupyter_text>3.3 The special string literals Eescape character (转意符）Eescape character begins with a backslash`\`You use to inform that the next character is special.|Escape Sequence| Control Character|| ---- |:----------:||\n |Newline||\t| Horizontal tab||\v |Vertical tab||\b| Backspace||\r |Carriage return||\f |Form feed||\a| Alert/bell|<jupyter_code>print('escape character\n 99999') 
print('escape character')

print('\t escape character')<jupyter_output><empty_output><jupyter_text>*r'string'* raw string literals **r'string'** raw string literals produce a string just like a normal string literal does<jupyter_code># r'' raw string literals produce a string just like a normal string literal does。
print(r'escape character\n99999')
print(r'\t escape character')<jupyter_output><empty_output><jupyter_text>4 Input & Type Conversion 4.1 InputPython 3 has a function, `input`, that can be used to get input directly from a user.It takes a string as an argument and displays it as a prompt in the shell. It then waits for the user to type something, followed by hitting the enter key.<jupyter_code>name = input('Enter your name: ')
print('Are you really', name, '?')<jupyter_output><empty_output><jupyter_text>The line typed by the user treated as a string and becomes the value returned by the function.if you type 3,the variable `n` is bound to the **string** `'3'` not the **int** `3`.<jupyter_code>n = input('Enter an int: ')
type(n)

n+1<jupyter_output><empty_output><jupyter_text>if  you want to get integer 3,you must conversion string ri integer<jupyter_code>n=int(n)
n+1<jupyter_output><empty_output><jupyter_text>4.2 Type ConversionType conversions(also called type casts) are used often in Python code.  We use **the name of a type** to convert values to that type.* `int(x)` converts x to an integer. * `float(x`) converts x to a floating-point number. * `str(x)` converts object x to a string representation.<jupyter_code>n="2"
a=int(n)
a
type(a)<jupyter_output><empty_output><jupyter_text>When `a float` is converted to an `int`, the number is truncated (not rounded), e.g.,<jupyter_code>number=3.1
int(number)
int("2.3")
float(1)
str(2.1)
str(123)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11096938775510204, 'fraction_numerical': 0.021581632653061223, 'mean_word_length': 4.868562874251497, 'pattern_counts': {'":': 0, '<': 188, '<?xml version=': 0, '>': 185, 'https://': 6, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 2, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '40', 'dir': 'jupyter-structured-clean-dedup', 'id': '232888', 'license': 'MIT', 'n_tokens_mistral': 6370, 'n_tokens_neox': 6043, 'n_words': 2368, 'path': 'notebook/Unit1-1-Introduction_Python.ipynb', 'repo_name': 'SEU03013050/notebook', 'size': '19610'}