Python Notes: Chapter One

Introduction to Python

1. The Origin and Versions of Python

1.1 Origin of Python

The founder of Python is Guido van Rossum. During Christmas in 1989, Guido van Rossum (Chinese name: Turtle Uncle) decided to develop a new scripting interpreter to pass the time in Amsterdam, as a successor to the ABC language.

1.2 Python Versions

The main versions of Python currently are Python 2.7 and Python 3.6.

The Python 2 version will no longer be maintained after 2020.

2. What Kind of Language is Python

Programming languages are mainly classified from several perspectives: compiled and interpreted, static and dynamic languages, strongly typed and weakly typed languages. What does each classification mean? Let’s take a look.

2.1 Compiled Languages and Interpreted Languages

Compiled languages: When a user finishes writing a piece of code that needs to be executed, the compiler compiles the entire code into a binary file that the computer can understand, and then executes it.

In this process, if the user’s code contains errors, the compiler must start compiling from the beginning. This might not be noticeable with just a few lines or pages of code, but if the code consists of thousands or even millions of lines, it can waste a lot of time and slow down development.

Moreover, it is not cross-platform; compiled code cannot be executed on different operating systems. Its advantage is speed, as once compiled successfully, it can be executed directly each time it is called.

Representatives of compiled languages: C, C++

Interpreted languages: When a user finishes writing a piece of code that needs to be executed, the interpreter interprets it piece by piece into a binary file that the computer can understand and executes it directly.

Unlike compiled languages, if the user’s code contains errors, the interpreter does not need to start over, which greatly saves development time. Additionally, it is portable; different operating systems can interpret it with different interpreters.

Its disadvantage is slower execution speed, as it needs to interpret line by line each time it is executed.

Representatives of interpreted languages: JavaScript, PHP, Python

2.2 Dynamic Languages and Static Languages

Dynamic languages: Dynamic languages check the data type of a variable only at runtime, meaning that when writing code, there is no need to specify the type of a variable in advance.

When a variable is first assigned a value, the language stores the data type of that variable in memory. Python and Ruby are typical representatives of dynamic languages.

Static languages: Static languages check each variable’s data type during compilation, so users must declare each variable’s data type before writing the program. Java, C, and C++ are representatives of static languages.

2.3 Strongly Typed Languages and Weakly Typed Languages

Strongly typed languages: Once a variable is assigned a data type, it will always be of that type unless it is forcibly converted (e.g., int(), str()). For example, if a = 1, then any subsequent assignment to a must also be of integer type.

Weakly typed languages: A variable can be assigned different data types at different times, meaning that a variable’s data type can be ignored.

In summary, Python is a dynamically interpreted strongly typed language.

3. Advantages and Disadvantages of Python

Advantages:

▷ Elegant, clear, concise

▷ Portable, extensible, embeddable

▷ High development efficiency

Disadvantages:

▷ Slow execution speed

▷ Code cannot be encrypted

▷ Cannot use multithreading

4. Types of Python

CPython

When we download and install Python 3.6 from the official Python website, we directly obtain the official version of the interpreter: CPython. This interpreter is developed in C, hence the name CPython. Running python in the command line starts the CPython interpreter.

CPython is the most widely used Python interpreter. All the code in this tutorial is executed under CPython.

IPython

IPython is an interactive interpreter built on top of CPython, meaning that it enhances the interactive capabilities while having the same functionality for executing Python code as CPython. It’s like many domestic browsers that look different but actually call the same underlying engine.

CPython uses >>> as the prompt, while IPython uses In [number]: as the prompt.

PyPy

PyPy is another Python interpreter that aims for execution speed. PyPy uses JIT technology to dynamically compile Python code (not interpret it), significantly improving the execution speed of Python code.

Most Python code can run under PyPy, but there are some differences between PyPy and CPython, which can lead to different results when the same Python code is executed under both interpreters.

Jython

Jython is a Python interpreter that runs on the Java platform, allowing Python code to be directly compiled into Java bytecode for execution.

IronPython

IronPython is similar to Jython, but it runs on the Microsoft .Net platform and can compile Python code directly into .Net bytecode.

Summary:

There are many Python interpreters, but the most widely used is still CPython. If you need to interact with Java or .Net platforms, the best way is not to use Jython or IronPython, but to call through the network to ensure the independence of each program.

5. Python Environment Configuration   

1

1. Download the installation package
 https://www.python.org/downloads/
2. Install
Default installation path: C:\python27
3. Configure environment variables
【Right-click Computer】-->【Properties】-->【Advanced System Settings】-->【Advanced】-->【Environment Variables】-->【In the second content box, find the line with variable name Path, double-click】 -->
【Append the Python installation directory to the value, separated by ;】
For example: Original value;C:\python27,
Make sure to have a semicolon in front in English input state

6. Basic Python

1. Writing and Running Python Code

▷ Create a file named test.py on drive E and write the following code:

print("Hello World!")

▷ Press the shortcut key win+R to open the run window, then enter cmd to open the command line window.

Python Notes: Chapter One

▷ In the command line window, enter python e:/test.py Python Notes: Chapter One

The above image shows that the file code was successfully run and printed “Hello World!”

2. Content Encoding

When the interpreter executes the code, it needs to compile the code into binary code that the machine can read (composed of 1s and 0s). The Python 2 version defaults to ASCII format during compilation (encoding format can also be specified), while Python 3 defaults to utf-8 format during compilation.

ASCII (American Standard Code for Information Interchange) is a computer encoding system based on Latin letters, mainly used to display modern English and other Western European languages, and can represent at most 256 symbols (one byte), i.e., 2**8 = 256.

However, the number of languages and symbols in the world far exceeds 256, so when computers were introduced globally, ASCII could no longer meet everyone’s needs, leading to the emergence of Unicode (Universal Code, National Code, Single Code). Unicode was created to solve the limitations of traditional character encoding schemes, providing a unified and unique binary code for each character in each language, specifying that most characters and symbols should be represented by at least 16 bits (2 bytes), i.e., 2 ** 16 = 65536. Note: This means at least 2 bytes, potentially more.

But a problem arises: since Unicode requires at least 2 bytes (16 bits), English letters and some symbols do not need this much space, so using Unicode for everything would waste valuable memory. Thus, a new encoding emerged: UTF-8. This encoding format compresses and optimizes Unicode encoding, no longer using a minimum of 2 bytes, but classifying all characters and symbols: contents in ASCII are saved in 1 byte, European characters in 2 bytes, and East Asian characters in 3 bytes…

Therefore, when the Python interpreter loads code from a .py file, it will encode the content (defaulting to ASCII). If the code is as follows:

Error: ASCII cannot represent Chinese characters

print('你好,世界!')

The solution is to add the following code at the beginning of the code to specify the encoding format:

#-*- encoding:utf-8 -*-
# This way, it can successfully execute and print "你好,世界!".

3. Comments

Single-line comment: # Commented content

Multi-line comment: ”’Commented content”’, or “””Commented content”””

4. Variables

A variable is a way to store intermediate results of program execution in memory for later use.

▷ Declare a variable

1 # -*- coding: utf-8 -*-
2 
3 name = "fuyong"

The above code declares a variable named: name, with the value of the variable name being: “fuyong”.

The role of the variable is a nickname, representing the content saved at a certain address in memory.

▷ Variable Naming Rules

1. Composed of letters, underscores, and numbers

2. The first character cannot be a number

3. Cannot be a keyword in Python (the following are Python keywords)

['and', 'as', 'assert',
 'break', 'class', 'continue', 
 'def', 'del', 'elif', 'else', 
 'except', 'exec', 'finally', 
 'for', 'from', 'global', 'if', 
 'import', 'in', 'is', 'lambda',
 'not', 'or', 'pass', 'print',
 'raise', 'return', 'try', 
 'while', 'with', 'yield']

▷ Variable Assignment

Variable assignment actually allocates a block of data in memory and points that data to the variable name, allowing the variable name to find the corresponding value when called.

If the value of one variable is assigned to another variable, there is still only one data value in memory, just pointed to by two different variable names.

5. Constants

Constants refer to unchanging values, such as pi 3.141592653…, or values that do not change during program execution.

In Python, there is no specific syntax for constants; programmers conventionally use uppercase variable names to represent constants (in reality, this constant can also be changed).

:Bir_of_China = 1949

6. User Interaction (input)

1 # -*- coding: utf-8 -*-
2 
3 # Assign the user's input to the variable name
4 name = input("Please enter your username:")
5 
6 # Print the input content
7 print(name, age)
# When executing the script, you will find that the program waits for you to input your name before proceeding.

7. Basic Data Types

▷ int Integer
On a 32-bit machine, the length of int is 32 bits,
Range: -2**31 -- 2**31-1 
On a 64-bit machine, the length of int is 64 bits,
Range: -2**63 -- 2**63-1

▷ long Long Integer (no longer exists in Python 3, all numbers are of int type)
Unlike C, Python's long integers do not have a specific width,
meaning: Python does not limit the size of long integer values,
but in reality, due to limited machine memory,
the long integer values we use cannot be infinitely large.
This type does not need special definition by the user,
when a number exceeds the range of int data type,
it will automatically convert to long integer.
Note: Python 3 no longer has the long type; all are int types.

▷ bool Boolean Type (True False)
True: 1, 1==1,
2>1, type('a')
== str results in True
False: 0,
1!=1,
2>3, etc., results in False

▷ str String Type
Simply put, in Python,
any characters enclosed in quotes are considered strings,
even if they are numbers ('123')
1 >>> name = "Alex Li" # Double quotes
2 >>> age = "22"  # As long as it's enclosed in quotes, it's a string
3 >>> age2 = 22   # int
4 >>> 
5 >>> msg = '''My name is Alex,
 I am 22 years old!'''  
# Wow, three quotes also work
6 >>> 
7 >>> hometown = 'ShanDong'  
 # Single quotes also work

Single quotes, double quotes, and triple quotes can all represent strings.

Single and double quotes can be used together, as follows:

msg = "I'm a small bird"

Triple quotes can assign a large block of code to a variable, as follows:

1 msg = '''
2 Today I want to write a little poem,
3 praising my deskmate,
4 Look at his black short hair,
5 It looks like a fried chicken.
6 '''
7 print(msg)
Strings can be concatenated using +, but both must be of string type.
1 a = 'hello'
2 b = 'xiaomi'
3 c = a + b
4 print(c)

The printed result is “helloxiaomi”.

Strings can also be multiplied by a number, resulting in the string being repeated N times, as follows:

print('xyz' * 3)

# The output will be 'xyzxyzxyz'

8. Formatted Output

There is an exercise requirement to ask the user for their name, age, job, and hobby, then print it in the following format:

------------ info of fuyong -----------Name  : fuyong
Age   : 29
job   : none
Hobbie: girl
------------- end -----------------

How can we achieve this? You will find that using string concatenation is difficult to achieve this format, so let’s learn a new technique.

We just need to prepare the format to print. Since some information needs user input, we cannot preset it, so we can place a placeholder and map the placeholders in the string to external variables.

1 name = input("Please enter your name:")
 2 age =  input("Please enter your age:")
 3 job = input("Please enter your job:")
 4 hobbie = input("Please enter your hobby:")
 5 
 6 info = ''' 
 7  ------------ info of %s ----------- # Placeholder waiting for name value
 8     
 9 Name:%s  
# Placeholder waiting for name value
10 
11 Age :%s  
# Placeholder waiting for age value
12 
13 Job :%s  
# Placeholder waiting for job value
14 
15 Hobbie:%s 
# Placeholder waiting for hobbie value
16 
17 ------------- end -----------------
18 
19 ''' %(name, name, age, job, hobbie) 
# The values in parentheses after the % correspond to the placeholders above,
20 # mapping the values in one-to-one correspondence
21 print(info)

Note: If the string needs to contain a ‘%’, it must use the escape character, as follows:

msg = "I am %s, age %d,
 my current learning progress is 80%%"%('Jinxin', 18)
print(msg)

PS:

▷ The method to check the data type is type()

For example, type(1) results in int, type(‘a’) results in str.

▷ If a variable is an Arabic numeral, its data can be converted between int type and str type.

9. Basic Operators

▷ Arithmetic operations      Python Notes: Chapter One

▷ Comparison operations    Python Notes: Chapter One

▷ Assignment operations Python Notes: Chapter One

▷ Logical operations   Python Notes: Chapter One

Note: Without parentheses, the priority is not > and > or. That is, () > not > and > or. In the case of the same priority, calculations are performed from left to right. Python Notes: Chapter One

10. Control Flow: Conditional Statements

In reality, we often have many choices. For example, when walking, if we encounter a fork in the road, we can only choose one path. The same applies to programs; if there are branches, we use if statements to control the flow.

if condition:  
# Condition can be a comparison, logical, or boolean operation
 execute statements
else:
 execute statements

# Note: if and else must be followed by a colon ':'
# The statements following if and else must be indented
name = input('Please enter your username:')
password = input('Please enter your password:')
if name == 'fuyong' and password == '123':
 print('Congratulations, login successful')
 else:
print('Sorry, username or password incorrect!')

The if statement can be nested, as the above code can be modified as follows:

name = input('Please enter your username:')
password = input('Please enter your password:')
if name == 'fuyong':
 if password == '123':
 print('Congratulations, login successful')
 else:
print('Sorry, username or password incorrect!')

if else can also have multiple branches using elif, as follows:

num = input('Please enter a number'):

if num == 1:
 print("You chose number 1")

elif  num == 2:
 print("You chose number 2")

elif num == 3:
 print('You chose number 3')

else:
 print('Input error, please choose from 1, 2, or 3')

11. Control Flow: Loops    

During program writing, sometimes we need to execute a piece of code repeatedly many times. If we write it out each time, it not only takes up a lot of space but also becomes very unattractive, which goes against Python’s principle of ‘elegance, clarity, and simplicity’. In this case, we can solve the problem with a loop statement. The format is:

while condition: 
# Similar to the if statement, the condition can be a comparison, logical, or boolean operation
 loop body 

We control the number of loop iterations through the condition, as follows:

n = 0
while n < 3:
 print("This line will be executed 3 times")
 n = n + 1

We can use the keywords break and continue to terminate loops.

break exits the entire loop, executing the code outside the loop body.

continue skips this iteration of the loop, returning to the start of the loop.

count = 0
while True:
 print("If not count,
 I will keep printing until your computer explodes")
 if count == 5:
 break
 count = count + 1

The above example shows that as long as break appears, the loop will immediately terminate regardless of whether the condition remains True.

1 n = 0
 2 
 3 while n < 10:
 4 
 5   n = n + 1
 6 
 7  if n == 4:
 8 
 9   continue
10         
11  print(n,"I just don't want to print '4'")
12 
13     
14        

The execution result of the above code is:

1 1 I just don't want to print '4'
 2 2 I just don't want to print '4'
 3 3 I just don't want to print '4'
 4 5 I just don't want to print '4'
 5 6 I just don't want to print '4'
 6 7 I just don't want to print '4'
 7 8 I just don't want to print '4'
 8 9 I just don't want to print '4'
 9 10 I just don't want to print '4'
10 >>>

The above example shows that when continue appears, this iteration is skipped, but it will return to the first statement of the loop body to check if the condition is True.

In other languages, else usually pairs with if, but in Python, else can also pair with while. The format is:

1 while condition:
2 
3     loop body
4 else:
5 
6 If the loop executes normally and is not terminated by break, this code will be executed

12. Homework Exercises

1. Use a while loop to input 1 2 3 4 5 6 8 9 10

1 count = 0
 2 
 3 while count < 10:
 4 
 5     count = count + 1
 6     
 7     if count == 7:
 8         continue
 9     
10     print(count)

2. Calculate the sum of all numbers from 1 to 100

1 count = 0
 2 
 3 sum = 0
 4 
 5 while count < 100:
 6 
 7     count = count + 1
 8 
 9     sum = sum + count
10 
11 print(sum)

3. Output all odd numbers from 1 to 100

1 count = 0
 2 
 3 
 4 while count < 100:
 5 
 6     count = count + 1
 7 
 8     if count % 2 == 1:
 9         print(count)
10        

4. Output all even numbers from 1 to 100

1 count = 0
 2 
 3 
 4 while count < 100:
 5 
 6     count = count + 1
 7 
 8     if count % 2 == 0:
 9         print(count)
10        

5. Calculate the sum of all numbers from 1-2+3-4+5 … 99

1 count = 0
 2 sum = 0
 3 
 4 while count < 99:
 5 
 6     count = count + 1
 7 
 8     if count % 2 == 0: 
# If it's an even number, the operator is +
 9         sum = sum - count
10 
11     else:
12         sum = sum + count
# If it's an odd number, the operator is -
13 
14 print(sum)
15        

6. User Login (three chances to retry)

1 count = 0
 2 
 3 while True:
 4 
 5 name = input('Please enter your username:')
 6 password = input('Please enter your password:')
 7 
 8 if name == 'fuyong' and password == '123':
 9 print('Congratulations, login successful!')
10 
11 break
12 
13 else:
14  print('Username or password incorrect,
     please re-enter:')
15 
16 count = count + 1
17 
18 if count == 3:
19 print('Sorry, you have entered incorrectly 3 times,
   the login program terminates')
20 
21  break

Source: http://www.cnblogs.com/fu-yong/p/8060188.html

Follow Us

Python Notes: Chapter One

Leave a Comment