Python environment construction and input and output

Python environment construction and input and output

1. Overview of Python

1. Computer resources

In the field of development, computer resources can be divided into two parts: software resources + hardware resources

==Software resources: visible, intangible==

==Hardware resources: visible and tangible==

Hardware resources (CPU, memory, hard disk, fan, power supply, keyboard, mouse...)

Software resources (Office software, Netease cloud music, various computer games)

Thinking: We found that software and hardware can actually interact. What is the principle of this?

Answer: Use the operating system, == operating system == is a bridge between computer software and hardware

2. Operating system classification

In daily applications, operating systems can be roughly divided into three categories:

① Windows operating system (personal version, server version Windows Server)

② MacOS operating system (personal version, the bottom layer is based on UNIX operating system)

Closed source charging operating system

③ Linux operating system (the operating system with the largest server usage, Ubuntu Ubuntu operating system, CentOS7 operating system)

Open source free operating system

The Python language involves more than 70% of the technical fields of the IT industry

4. The birth of the Python language

In 1989, in order to pass the Christmas holiday, Uncle Turtle (Guido van Rossum) began to write a compiler for Python language. In 1991, the first Python compiler was born. The name Python comes from Monty, a TV series that Uncle Guido loves. Python's Flying Circus (Monty Python's Flying Circus)

5. Advantages and disadvantages of Python language

advantage

Simplicity: Python is a language that represents the idea of ​​simplicity. Reading a good Python program feels like reading English, and this code nature of Python is one of its greatest strengths. It enables you to focus on solving problems rather than understanding the language itself.

Easy to learn: As you will see, Python is extremely easy to learn. As mentioned earlier, Python has an extremely simple syntax.

Free and open source: Python is open source. Simply put, you are free to read its source code and make changes to it. This is one of the reasons why Python is so good. It is created and constantly improved by a group of people who want to see a better Python. .

Portability: Due to its open source nature, Python has been ported (modified to make it work on different platforms) on many platforms. If you are careful to avoid system-dependent features, all your Python programs will run without modification on any of the platforms described below.

Rich library: The Python standard library is indeed huge. It can help you with a variety of tasks, including regular expressions, documentation generation, unit testing, threads, databases, web browsers, CGI, FTP, email, XML, XML-RPC, HTML, WAV files, cryptosystems, GUI (graphical user interface), Tk and other system-related operations. Remember, all of these features are available as long as Python is installed. This is called the "full-featured" philosophy of Python.

shortcoming

The Python language is very complete and has no obvious shortcomings or shortcomings. The only shortcoming is slow execution efficiency, which is common to interpreted languages. At the same time, this shortcoming will be made up for by the increasingly powerful performance of computers.

6. Selection of Python version

Python3.x

Python3.6、==Python3.7==、Python3.8、Python3.9...

In a production environment, we generally do not choose the latest version of Python, because there may be unknown bugs, so it is generally strongly recommended that you push forward 1 to 2 versions when selecting a software version. So our course mainly explains the Python3.7 version.

2. Python parser

1. The role of the Python parser

demo.py

print('Hello World')

Since Python is a high-level language, it cannot be run directly on the computer because of the lack of a Python language operating environment: Python parser

The function of the Python parser: == is to convert the Python code into a machine language that can be recognized by the bottom layer of the computer ==, such as 0101...

2. Types of Python parsers

==① CPython, an interpreter developed in C language [official], a widely used interpreter. ==

② IPython, an interactive interpreter based on CPython.

③ Other interpreters

PyPy, an interpreter based on the Python language.

JPython, an interpreter running on the Java platform, directly compiles Python code into Java bytecode for execution.

IronPython, a Python interpreter running on the Microsoft .Net platform, can directly compile Python code into .Net bytecode.

3. Download the Python parser

Download address: Python Release Python 3.7.9 | Python.org

[Click on the above link] -- Find the target file: Windows x86-64 executable installer -- Single

Click to download.

4. Installation of Python parser

Step 1: Double-click the parser to run Python, select ==Custom Installation== and ==Add Python to Environment Variables==

Step 2: Select all the function menus to be installed, all are checked by default

pip: Python's package management tool, which can be used to install various modules that we need to use in our projects in the future

Step 3: Set the installation path of the Python parser. It is strongly recommended to install it on a drive letter other than the C drive

Step 4: Test whether the Python parser can be used

Press Windows + R, enter the cmd character, open the Windows DOS window, and enter python (all lowercase), as shown in the figure below:

When the above interface appears, it means that the Python3.7 parser has been installed successfully. How to exit to DOS mode from this window?

Answer: Use the exit() method

>>> exit() 回车

3. Python development tool PyCharm

1. Why install PyCharm

If a worker wants to do a good job, he must first sharpen his tools

In the field of Python development, there are many development tools, such as EditPlus, Notepad++, Sublime Text3, Visual Studio Code, PyCharm (currently the most powerful IDE)

2. The main function of PyCharm

PyCharm is a Python IDE (Integrated Development Environment), with a set of tools that can help users improve their efficiency when developing in the Python language. The internal integrated functions are as follows:

Project management

Smart Tips

syntax highlighting

code jump

debug code

interpret code (interpreter)

Frameworks and Libraries

......

3. Classification of PyCharm

There are two versions of PyCharm: Professional Edition (paid) and Community Edition (free, open source)

In the basic class, the PyCharm community edition is enough for us, more than enough.

4. Download PyCharm

Download link: Download PyCharm: Python IDE for Professional Developers by JetBrains

5. PyCharm installation

Step 1: Double-click the PyCharm software installation package to install the software

Step 2: Set the installation path of the software. There is no requirement in theory, but it is recommended to put it in a drive letter other than the C drive

Step 3: PyCharm basic settings, create a desktop icon and associate it with a .py file

Step 4: Run PyCharm, choose a free trial, and click Evaluate

Step 5: Click Continue

6. Use of PyCharm software

☆ Create a Python project

What is a project? In fact, in our actual development, every time we participate in the development of a job is a project development process. So the first thing to do with PyCharm is to learn the process of creating a Python project.

Step 1: Create a project

Step 2: Set the project path, which must be placed on a drive letter other than the C drive (very important!!!)

After the configuration is complete, create a Python project on the stand-alone Create.

☆ New file and code writing

If you want to upload files to the server in the future, remember not to use Chinese in the file name.

Write Hello World

print('Hello World')

☆ Run the code

operation result:

☆ Set or change Python parser

Open the File file and find the Settings setting, as shown in the figure below: Replace the Python parser

☆ PyCharm software itself settings

① Software theme (the future style of software)

② Code font setting

③ Code font size setting (text size)

Open the File file => Settings and find the interface settings:

Theme settings:

Font and font size settings:

Font settings:

Font size setting:

☆ Open project and close project

Open project: The project itself already exists, so we open it directly.

Select the project directory (folder), as shown in the following figure:

① This Window => Overwrite the current project to open the target project

② New Window => open in a new window, then open PyCharm twice, each PyCharm is responsible for a project

③ Attach => Merge two projects together and put them in the same window

Close project: close the running project.

4. Python comments

1. The role of annotations

First of all, one thing is emphasized: Python code => Python parser => machine language, but the comment will not be parsed and executed by the Python interpreter. Because its main purpose is to comment on the code.

Comment function: ==Improve the readability of the code==

When we write Python programs, in order to improve the readability of the program, it is strongly recommended that you add comments to the core code.

2. The basic syntax of Python comments

☆ Single-line comments

Single-line comments, starting with "#" (Shift + 3), can only comment one line

# Comment content

Sample code:

The first type: above the line of code

# Output Hello World string 
print('Hello World')

The second type: put it behind the code (reserve 2 spaces after the code)

print('Hello World') # output Hello World string

☆ Multi-line comments

Multi-line comments: Multiple lines of code or programs can be commented at the same time, often used for code block comments

Basic syntax:

""" 
Comment content 
first line 
second line 
third line 
"""

or

''' 
Comment content 
first line 
second line 
third line 
'''

Sample code:

""" 
Hi, everyone, 
I am a dark horse programmer. 
Starting today, we will learn the language Python together. 
""" 
​'
'' 
Hi, everyone, 
I am a new employee. 
Starting today, we will We will learn the language Python together 
''' 
print('Hi, everyone') 
print('I am a new employee') 
print('From today, we will learn the language Python together')

☆ PyCharm annotation tips (shortcut keys)

In PyCharm, we can use Ctrl + /斜杠to quickly comment on the code or program.

Five, PyCharm commonly used shortcut keys

1. Code prompt

In PyCharm, when we enter the first 2~3 characters in the Python keyword, it will automatically prompt the code. At this time, we only need to press Enter to quickly enter something.

2. Save the code

When writing code, you must develop a good habit of Ctrl + Ssaving the code quickly.

Personal suggestion, when you finish writing a line of code, press it once.

3. Revocation and restoration

If you accidentally delete a line of code, we can quickly Ctrl + Zrestore it at this time. Every time you press it, you cancel once. What should you do if there are too many undoes?

Answer: You can also Ctrl + Yperform recovery operations by

6. Variables in Python (emphasis)

1. Variable learning objectives (case)

Case: Realize the exchange of two variables

Cup No. 1: Coke (cola)

cup 2: milk (milk)

After a series of Python operations

Cup No. 1: milk (milk)

Cup No. 2: Coke (cola)

2. Introduce the concept of variables

What is Quantity: Quantity is the smallest unit in a program.

So what is a variable?

==① Variables are containers for storing data==

==② Variables can be changed during the running of the program==

==③ The data stored in the variable is temporary==

3. The role of variables (give a chestnut)

Taobao registration case:

① Write user name and password

==② The Python program needs to receive the user name and password (temporary storage) ==

③ Permanently store the user name and password received just now (database)

In order to solve the above problems, Python has developed the concept of variables, which can temporarily save some information entered by users. The saved container is a Python variable.

4. Definition of variables

Basic syntax:

Variable name = variable value 
Note: There must be a space on both sides of the equal sign. In fact, it is recommended to keep a space on both sides of the symbol in Python.

Explanation: In the Python program, this equal sign is different from the equal sign in daily life. It has a professional term: assignment operator, and its reading method: read from right to left, and assign the value of the variable to variable on the left.

5. Variable naming rules

The identifier naming rule is a naming convention when defining variable names in Python, as follows:

==① Composed of numbers, letters, and underscores (_) ==

==② Cannot begin with a number==

==③ Strictly case-sensitive==

==④ Cannot use built-in keywords as variable names==

Underscore => Shift + - minus sign

Take a chestnut:

① abc, abc123, _abc, hello (reasonable)

② 123abc, @abc, abc-123 (unreasonable)

③ _ (underscore) => Can this be a variable name? Answer: yes

for _ in range(10):
    ...

Note: When naming Python variables, it is not recommended to use the beginning of _, because it conflicts with the private attributes to be learned later

④ Are the variable abc and the variable ABC the same variable? Answer: No, these are two completely different variables

⑤ What if I can’t remember the Python keywords? Answer: With help() method

>>> 
help('keywords')

6. Recommended variable naming rules

① Variable naming must be clear from the name.

② Big hump: the first letter of each word is capitalized, for example: MyName.

③ Small camel case: capitalize the first letter of the word after the second (inclusive), for example: myName .

④ Underline: For example: my_name.

7. Variable definition and call

In Python, remember: variables must be defined first and then used, otherwise an error will be reported.

definition:

name = 'itCes'
address = '北京市西城区庄胜广场'

transfer:

print(name)
print(address)
或
print(name, address)

8. Frequently asked questions about the definition and use of variables

① How to distinguish between variables and strings:

==In Python, if single quotes or double quotes are added to the content to be assigned, it is a data type in Python: it is called a string (text information in daily life)==

② When print prints variables, I like to add quotation marks to them

print(name) # output the value corresponding to the variable name 
and 
print('name') # output the string 'name'

③ PyCharm shortcut key => Ctrl + Alt + L=> code formatting

Seven, the data type of variables in Python

1. Why learn data types

The definition of variables is very simple, but many friends may think: In addition to storing data of this character type, can variables store other types of data? In fact, in Python, in order to meet different business needs, we also divide data into different types, as shown in the following figure:

Interview question: Please handwrite the 7 data types in Python?

Answer: numeric type, Boolean type, string type, list type, tuple type, collection type, dictionary type

Today we only need to understand the first three.

Question: How to determine what type a variable is?

Answer: ① Use the type (variable name) method to return the data type of the variable ② isinstance (variable name, data type), which can only return True or False (true or false)

2. Value type

The numerical type is the number in our daily life, and the number is divided into two forms: integer and decimal (with decimal point)

Integer type: int type

Decimal type: float type

Case 1: Define the information of a person, name: Tom, age 18

name = 'Tom'
age = 18
print(type(age))

Case 2: Define a supermarket cash register system, write a name: Chinese cabbage, price: 3.5

name = '大白菜'
price = 3.5
print(type(price))

3. Boolean type

The Boolean type is a data type related to logic and has only two values: True (true) and False (false)

Case 1: Manually define a flag variable whose value is True

flag = True
print(flag)
print(type(flag))

In fact, in Python, the return result of many programs can also be True or False, such as isinstance()

num = 10
print(isinstance(num, int))  # True
print(isinstance(num, bool))  # False

4. String type

In the Python variable definition, if the content of its assignment is enclosed by single or double quotation marks, it is the string str type.

msg = '这家伙很懒,什么都没有留下...'
print(type(msg))

5. Other types (understand)

# 1、list列表类型
list1 = [10, 20, 30, 40]
print(type(list1))
​
# 2、tuple元组类型
tuple1 = (10, 20, 30, 40)
print(type(tuple1))
​
# 3、set集合类型:去重
set1 = {10, 20, 30}
print(type(set1))
​
# 4、dict字典类型:查询、搜索
dict1 = {'name':'itheima', 'age':18}
print(type(dict1))

8. Understanding Bugs in Python

1. Know about bugs

The so-called bug is an error in the program. If there is an error in the program, we need our programmers to troubleshoot and correct the error in time.

2. Solve bugs in three steps (compilation errors)

Step 1: View the error page

Step 2: Look at the wrong line number

The third step: according to the specific error, specific analysis

3. PyCharm code debugging (runtime error)

The Debug tool is a special tool for debugging programs integrated in PyCharm IDE, where programmers can view the execution details and process of the program, so that we can quickly find out the bugs of the program!

The Debug tool uses two steps: ==① Break point ② Debug debugging==

Note: Debug can also be used to understand the running process of the program

4. Next breakpoint

Where should the breakpoint be placed: A: The first line of the code segment where the code may go wrong

5. Debug debugging

6. Single-step debugging

If you encounter a small lightning icon, it means this row, and something may be wrong.

9. Formatted output in Python

1. Formatted output

So far, all of our output has been printed directly via the print(variable name) form. But in actual work, we may need to format the output of variables (==output in a certain format==).

Formatting of variables

2. Percent formatted output

Basic syntax:

...
print(变量名称)
print('字符串%格式' % (变量名称))
print('字符串%格式 %格式 %格式' % (变量名称1, 变量名称2, 变量名称3))

The common form of the % format is as follows:

formatting symbols convert
==%s== string
==%d== signed decimal integer
==%f== floating point number
%c character
%u unsigned decimal integer
%o octal integer
%x hexadecimal integer (lowercase ox)
%X Hexadecimal integer (uppercase OX)
%e scientific notation (lowercase 'e')
%E scientific notation (capital 'E')
%g Shorthand for %f and %e
%G Shorthand for %f and %E

Case: Define two variables name='itheima', age=18, and output according to the following format: My name is itheima, and I am 18 years old this year.

Example: Define two variables title='Chinese cabbage', price=3.5, and output according to the following format: Vegetables are on sale today, and Chinese cabbage only costs 3.5 yuan/catties.

title = '大白菜'
price = 3.5
# 格式化输出“今天蔬菜特价了,大白菜只要3.5元/斤。"
print("今天蔬菜特价了,%s只要%.2f元/斤。" % (title, price))

In fact, in addition to %f can set the number of decimal places, %d can also fill in the serial number.

Case: define two variables id=1, name='itheima', and output according to the following format: name itheima, student number 000001

id = 1
name = 'itheima'
print("姓名%s,学号%06d" % (name, id))

3. The format method formats the output

Basic syntax:

...
print('字符串{}'.format(变量名称1))
print('{}字符串{}'.format(变量名称1, 变量名称2))

Case: Define two variables, name='Monkey King', mobile='18878569090', and output according to the following format "Name: Monkey King, contact information: 18878569090"

name = '孙悟空'
mobile = '18878569090'
print("姓名:{},联系方式:{}".format(name, mobile))

4. The format method abbreviates formatted output (recommended)

In versions after Python 3.6, in order to simplify the format output operation, a shorthand form is introduced:

name = '孙悟空'
mobile = '18878569090'
print(f'姓名:{name},联系方式:{mobile}')

5. Escape symbols in formatted output

In the string, if \t and \n appear, the meaning they represent is two escape characters

\t :制表符,一个tab键(4个空格)的距离
\n :换行符

case:

print('*\t*\t*')
print('hello\nworld')

Special note: == By default, after each print() method is executed, a \n newline character will be output. If you don't want the print() method to wrap, you can add an end parameter ==

print('*', end='')

10. Standard input in Python

1. Why do you need to enter

All of our programs so far have only output data to the user. But in actual work, we often enter and obtain user input information, such as password input in the banking system, and user login verification in Taobao.

2. input() input method

In Python, if you want a Python program to accept user input, you can use the input() method

Basic syntax:

input()

But often there is only the input() method, which has little meaning. We should also use a variable to temporarily accept user input, which is convenient for later operations.

Variable name = input('Prompt information:')

Case: In the banking system, the process of entering a password

password = input('请输入您的银行卡密码:')
print(f'您输入的银行卡密码为:{password}')

3. Important matters of input() method

Remember: all data obtained by the input() method is == "string" == type

name = input('请输入您的姓名:')
age = input('请输入您的年龄:')
​
print(type(name))  # <class 'str'>
print(type(age))  # <class 'str'>

summary:

① input() can be used to receive information input by external devices, but if the user does not input anything, the input() function will suspend the continued execution of the current code and wait until the end of the user input.

② All data obtained by the input() method are == "string" == type

Guess you like

Origin blog.csdn.net/qq_46020806/article/details/130881460