程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python zero basics beginner level chapter - 07 - Python script structure

編輯:Python

List of articles

    • Create a project and demo script
    • python Script structure
    • python Script execution
    • python Header notes for
    • python Import of [ modular ( Class library ) The introduction of ]
    • python The order of execution of the program
    • python Program comments
    • python Script execution entry
    • About Python Indentation rules in
    • Python Built in functions in input

In understanding python Before the script structure of , Let's create a script first

Create a project and demo script






python Script structure



python Script execution

stay Pycharm in , We have two ways to execute scripts .

One is to use the menu bar 、 The toolbar 、 Right click the... That appears “run xxxx”( Or shortcut key Ctrl + Shift + F10) Realization .



The other is to use Pycharm Of Terminal Command line terminal



python Header notes for


  • What is? python Head note

    • Written in python The first line of the script , With "#" The information indicated at the beginning is the header comment

because Python The source code is also a text file , therefore , When your source code contains Chinese , When saving the source code , You need to be sure to specify save as UTF-8 code . When Python When the interpreter reads the source code , To make it press UTF-8 Code read , We usually write these two lines at the beginning of the document :

```
# !/usr/bin/env python
# -*- coding:utf-8 -*-
perhaps
# coding:utf-8
```

The first line of comment is to tell Linux/OS X System , This is a Python Executable program , according to usr/bin/env Find the path python Run the program to run ,Windows The system ignores this comment ;

The second comment is to tell Python Interpreter , according to UTF-8 Code read source code , otherwise , The Chinese output you write in the source code may be garbled .

But now generally, I only write one line "#coding:utf-8" .


  • python The header annotation function

    • Header comments are not intended to serve the code , It is more called by the system or interpreter .
    • Tell the system Python Where is the interpreter ?
    • What is the encoding format of the script ?

  • Common header comments

    • Commonly used in China "# coding:utf-8" : Definition coding Rules tell the system what kind of coding format the script is
    • At present, it is seldom used "# !/usr/bin/env python" : Definition python The specified execution path of the interpreter [WIN The system does not take effect ]

python Import of [ modular ( Class library ) The introduction of ]


  • 1. What's being imported ?
    • What is imported is that python Some function blocks in are used in the current script
    • The function of not importing cannot be directly used in the current script ( except python Built in functions )

  • 2. Why do I need to import ?
    • It can be understood as B The script wants to borrow A Use the functions in the script , We need to A The functions in the script are imported into B Script

  • 3. First knowledge of import grammar
    • import os
    • import : Built in import function
    • os : Imported modules

Refer to a import A little case of

# coding:utf-8
import os
a = " The current path is :"
b = os.getcwd()
print(a, b)

The output is The current path is : /Users/xxxx/PycharmProjects/pythonlearn

python The order of execution of the program

How the sequence is executed ?

Here we look at an implementation “print” Script for function

 # coding:utf-8
print(" This is the first line 'print' Information ")
print(" This is the second line 'print' Information ")
print(" This is the third line 'print' Information ", end=",")
print(" This is the fourth line 'print' Information ", )
print("Hello", "World")

Above “print” The function is Python3.x Built in functions for (Python3.x Has become a built-in function ,Python2.x in ,print Keyword ). So what is a built-in function ?

The built-in function is python Standard library ( Language itself carries ) function ( Public function ), There's no need to make wheels again , There is no need to import , Functions that can be used directly . More generally, it can be understood that the built-in functions of the interpreter are built-in functions .

Now let's take a look at the first one we came into contact with python Built in functions “print”

print The translation is “ Print ” It means , Information can be displayed ( Print ) In the console (cmd) The function on ,print The function can change Python Almost all programs in the code can be printed out .

I understand "print" After the function , Now let's see "print" Syntax of functions print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)

  • objects – The plural , Indicates that multiple objects can be output at one time . When outputting multiple objects , Need to use , Separate .
  • sep – Used to space multiple objects , The default is a space .
  • end – Used to set what end . The default is line breaks \n, We can change it to something else .
  • file – File object to write .
  • flush – Whether the output is cached usually depends on file, But if flush The key parameter is True, The stream is forced to refresh .

The above “print” The script output of the function is shown in the following figure

Thus we can see that ,python The script is executed from top to bottom , Line by line .

"print" Function is what we learn python The first built-in function touched , In the follow-up learning process, we will touch the built-in functions improperly , In particular, in the chapter related to functions, we will also learn about the creation and execution of functions .

python Program comments

What is annotation ?

It won't be in the code python Directly executed statements

Why use comments ?

First of all 、 Make sure that the module , function , Methods and inline comments use the right style , They can tell you what the function of a piece of code is in natural language .

second 、 Annotations can help debug programs

Adding notes to the code is the basic function of comments , In addition, it has another practical function , It's used to debug programs .

for instance , If you think there might be a problem with a piece of code , You can comment this code first , Give Way Python The interpreter ignores this code , And then it runs again . If the program works properly , The error is caused by this code ; conversely , If the same mistake still happens , The error is not caused by this code .

Using comments during debugging can narrow down the scope of errors , Improve the efficiency of debugging program .

Three uses of annotations

  • Python There are single line and multi line comments in :

  • Python Middle single line comment with # start

  • Python The comments in the multiple lines are 6 Two double quotes and 6 Single quotes

Now let's take a look at a little exercise on annotation , It is convenient for us to understand notes more intuitively

# coding:utf-8
""" @Author:Neo @Date:2020/9/14 @Filename:04-notes.py @Software:Pycharm """
print(" No small effort , multiply 365 It's obvious that ")
print(" insist ! insist ! insist !")
print("-----------------------")
''' This script is used for annotation exercises Quotation marks are generally used in two scenarios 1. Applied at the beginning of the whole script , The function is to introduce the script to others 2. Explanation of function function , such as "print" There is such an explanation in the built-in function 3.Python Use in # Annotate , We are using # When ,# There should be a space behind the number 4. When commenting in the line , At least two spaces should be added in the middle '''
# Multi line annotation scenarios for double quotation marks and single quotation marks , In fact, there is no mandatory specification , But we should try to unify .
# Don't use double quotation marks for multi line comments , The following is a multiline comment in single quotation marks , Very unsightly ()
print(" Life is too short , I use Python") # This is a simple annotation exercise 

python Script execution entry

What is? python Script execution entry ?

To put it more generally , For example, there must be a gate entrance to a building , There must also be an entrance on the highway . therefore , Execution procedure , You also need an entrance ; Generally, the entry of code execution is called the main function (main function ).

For many programming languages , Every program must have an entrance , such as C,C++, And a completely object-oriented programming language Java,C# etc. .
If you've been exposed to these languages , The concept of program entry should be well understood ,C,C++ All need to have a main Function as the entry to the program , That is, the program will run from main Function to . Again ,Java,C# There must be an inclusion of Main The main class of the method , As program entry .

and Python Is different , It's a scripting language , Unlike a compiled language, which compiles programs into binary and then runs them , It's a dynamic line by line explanation run .
That is, starting from the first line of the script , No unified entrance .

One Python The source code file (.py) Besides being able to be run directly , It can also be used as a module ( That is, Ku ), By other .py File import .
Whether it's running directly or being imported ,.py The top-level code of the file will be run (Python Indent to distinguish code levels ), And be a .py When the file is imported as a module ,
We may not want some code to be run .

Let's take a look at the execution entry ( The main function ) Writing

if __name__ == '__main__':
print(os.getcwd())
print(" This is a python Script execution entry ")

About the above “ The main function ” Let's explain

  • Code in if It means : If the program you are running is your own , Then execute print(os.getcwd()) And print(" This is a python Script execution entry ")
  • Suppose you are running a.py This script , And this script has the main function , Then the main function will be executed
  • Suppose you are running b.py This script , Even if b.py Imported a.py , And will not execute a.py The main function inside (main function )

Then, is it necessary to execute the entry ( The main function )? Not necessarily , Suppose there is no main function , So run python Script when , Will be up and down , Run line by line python Script All the code for .

Since it is not necessary to execute the entry , So what is the meaning of the execution entry ? The purpose is to write the business code on the main function , The main function is used to call the business code , The code structure is clean and tidy Java、C、Golang par , They all require that a program must have a main execution entry to run correctly .

above ( The main function ) We can see in “print” There is a small blank space in front of the function , This leads to what we need to know next python The indent rule of .

About Python Indentation rules in

Different from other programming languages ( Here we have JAVA and C Language as an example ) Braces used “{ }” To separate code blocks , stay Python What is used in is Code indentation and The colon ( : ) To distinguish the layers between blocks of code .

stay Python in , For class definitions 、 Function definition 、 Flow control statement 、 Exception handling statements, etc , The colon at the end of the line and the indent of the next line , Indicates the beginning of the next block of code , The end of the indentation indicates the end of the code block .

It should be noted that ,Python Indent the code in , You can use spaces or Tab Key two ways to achieve . But whether it's manual typing spaces , Or use Tab key , Usually, we use 4 Space length as an indent ( By default , One Tab The key means 4 A space ).

About Python The indent rule of , Beginners can understand ,Python Require lines of code in the same scope , They must be indented by the same amount , But the exact amount of indentation , No hard and fast rules .

for example , The following paragraph Python In the code ( It involves what has not been learned yet , Beginners don't need to understand the meaning of the code , Just experience the indentation rules of code blocks )

a = 2
if a > 1:
print(" At present a The value is greater than 1") # Indent 4 Space occupying 
else: # And if alignment 
print(" At present a The value is less than 1") # Indent 4 Space occupying 

Now let's take a look at the fact that indentation is not so standard Python Code

a = 2
if a == 1:
print(" At present a The value is equal to the 2") # Indent 4 Space occupying 
else: # And if alignment 
print(" At present a The value of is not equal to 2") # Indent 4 Space occupying 
print(" end ")


stay Pycharm in We can intuitively see in 21 The red error identifier appears in the line code , Then run it for a try .



Throw out IndentationError: unexpected indent abnormal , The reason for this exception is the indentation exception ,Indentation It means indent , The scenario of this exception often appears in Spaces and Tab Indent mix Or is it Error in indent Under the circumstances , At this time, you need to check the corresponding code lines in the source code and repair the indentation problem .

This shows how important a good coding specification is , May refer to Python Zero foundation beginner level chapter - 06 - Python Several coding specifications that beginners need to keep in mind

Python Built in functions in input

input Function functions : Receive a standard input data , Return to string type ; Enter a line of information on the command line , This line of information is returned as a string .

input Function usage
usage :
result = input(' Please enter input Content ')
Parameters :
In parentheses is a prompt string , Inform the user of the known conditions that need to be filled in

Let's take a look at input Function demonstration chestnuts ( It involves what has not been learned yet , No need to understand the meaning of the code , Just experience input Function usage is OK )

name = input(" Please enter a name :")
birthday = input(" Please input birthday :")
sex = input(" Please enter gender :")
print(" Your name is :%s, The birthday is :%s, Gender is :%s " % (name, birthday, sex)) # '%s' Format string for 

The output is as follows :




  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved