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

Graphical Python | basic grammar

編輯:Python

author : Han Xinzi @ShowMeAI
Tutorial address :http://www.showmeai.tech/tutorials/56
This paper addresses :http://www.showmeai.tech/article-detail/66
Statement : copyright , For reprint, please contact the platform and the author and indicate the source


introduction

This series of tutorials will explain Python programing language , Before you learn specific grammar knowledge , Let's learn something first Python As a foundation for .

1. Content abstract

This article will Python Give a brief introduction , By reading this article, you will learn :

  • Python Programming model
  • Python Identifiers and keywords
  • Python Indents and code blocks
  • Python Simple input and output
  • Python Basic code structure

2. know Python Program

(1) Interactive programming

Interactive programming does not need to create script files , It's through Python The interpreter's interaction mode comes in to write code .
You just need to type... On the command line Python Command to start interactive programming , The prompt window is as follows :

$ python
Python 3.9.5 (default, May 4 2021, 03:33:11)
[Clang 12.0.0 (clang-1200.0.32.29)] on darwin
Type "help", "copyright", "credits" **or** "license" **for** more information.
>>>

stay python Enter the following text message at the prompt , Then press Enter Key to see the running effect :

>>> print("Hello, ShowMeAI, this is Python!")

In my current Python3.9.5 In the version , The output of the above example is as follows :

Hello, ShowMeAI, this is Python!

You can also use Previous section Mentioned Anaconda In the environment Jupyter Notebook Interactive Python Programming , start-up Jupyter Notebook And new Notebook as follows , You can go to cell Code writing and interaction in .

(2) Scripting

If the task we need to complete is more complex , We can organize the intermediate processing process into python Script , Then call the interpreter through the script parameters to start executing the script , Until the script is finished . When the script is finished , The interpreter is no longer valid .

Let's write a simple Python Script program . all Python The file will be .py Extension name . Copy the following source code to test.py In file .

print("Hello, ShowMeAI, this is Python!")

Use the following command to run the program :

$ python test.py

Output results :

Hello, ShowMeAI, this is Python!

3.Python identifier

Identifiers are allowed as variables ( function 、 Class etc. ) A valid string for the name . among , Part of it is keywords ( The identifier reserved by the language itself ), It cannot be used as an identifier for other purposes , Otherwise it will cause syntax errors (SyntaxError abnormal ).Python There is also called built-in Identifier set , Although they are not reserved words , But these special names are not recommended .

Python Is a dynamically typed language , That is, you don't need to declare the type of the variable in advance . The type and value of the variable are initialized at the moment of assignment . Variable assignment is performed by an equal sign .

Python A valid identifier for consists of upper and lower case letters 、 Underline and numbers make up . The number cannot be the first character , The length of the identifier is unlimited ,Python Identifiers are case sensitive .

In programming languages , There are two common ways to name variables :

  • Hump body :

    • DateOfBirth
    • AgeOfBoy
    • ShowMeAI
  • Underline :

    • date_of_birth
    • age_of_boy
    • show_me_ai

4.Python Reserved characters

The following list shows in Python Reserved word in . These reserved words cannot be used as constants or variables , Or any other identifier name .

all Python The keyword of contains only lowercase letters .

andexecnotassertfinallyorbreakforpassclassfromprintcontinueglobalraisedefifreturndelimporttryelifinwhileelseiswithexceptlambdayield

5. Lines and indents

Study Python The biggest difference from other languages is ,Python The code block of does not use braces {} To control the class , Functions and other logical judgments .python The most characteristic is to use indentation to write modules .

Indent can use tab Or spaces, etc , The number of blanks is variable , But all code block statements must contain the same amount of indented white space .

The following example is indented with four spaces :

if True:
print("True")
else:
print("False")

The following code will execute in error :

#!/usr/bin/python
# -*- coding: UTF-8 -*-
# file name :test.py
if True:
print("ShowMeAI")
print("Awesome")
else:
print("Test")
# There is no strict indentation , Error will be reported during execution
print("False")

Execute the above code , The following error alerts will appear :

 File "<stdin>", line 11
print("False")
^
IndentationError: unindent does not match any outer indentation level

Common alignment errors are 2 Kind of :

  • IndentationError: unindent does not match any outer indentation level

    • Error indication , You use different indents , There are plenty of them tab Key indent , There's space indentation , Change to consistent
  • IndentationError: unexpected indent

    • The format in the file is wrong , May be tab It's not aligned with the space

therefore , stay Python You must use the same number of indented spaces at the beginning of lines in the code block of .

I suggest you in actual programming , Use... For each indentation level Single tab or Two spaces or Four spaces , Remember not to mix

6. Multi line statement

Python In a statement, a new line is usually used as the end of the statement .

But we can use slashes ( \) Divide a line of statements into multiple lines to display , As shown below :

total = item_one + \
item_two + \
item_three

The statement contains [], {} or () Brackets do not need to use multiline connectors . The following example :

days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']

7.Python Strings and Quotes

Python You can use quotation marks ( ' )、 Double quotes ( " )、 Three quotes ( ''' or """ ) To represent a string , The beginning and end of a quotation mark must be of the same type .( More detailed python For string knowledge, see python String and operation )

Three quotation marks can be made up of multiple lines , Write fast syntax for multiline text , Commonly used for document strings , At the specific location of the document , As a comment .

word = 'word'
sentence = " This is a ShowMeAI A tutorial for ."
paragraph = """ This is a multi line statement .
One line contains ShowMeAI"""

8.Python notes

python Middle and single line notes use # start .

#!/usr/bin/python
# -*- coding: UTF-8 -*-
# file name :test.py
# The first note
print("Hello, ShowMeAI, this is Python!") # The second note

Output results :

Hello, ShowMeAI, this is Python!

Comments can be at the end of a statement or expression line :

name = "ShowMeAI" # This is a comment

python Use more than three quotes in a single line (''') Or three double quotes (""").

#!/usr/bin/python
# -*- coding: UTF-8 -*-
# file name :test.py
'''
This is a multiline comment , Use single quotes .
This is a multiline comment , Use single quotes .
This is a multiline comment , Use single quotes .
'''
"""
This is a multiline comment , Use double quotes .
This is a multiline comment , Use double quotes .
This is a multiline comment , Use double quotes .
"""

9.Python Blank line

Functions or methods of classes are separated by empty lines , Represents the beginning of a new piece of code . Classes and function entries are also separated by a blank line , To highlight the beginning of the function entry .

Blank lines are not the same as code indentation , Air travel is not Python Part of grammar . Don't insert blank lines when writing ,Python The interpreter will not run wrong . But blank lines are used to separate two pieces of code with different functions or meanings , Easy to maintain or refactor the code in the future .

10. User input

The following program will wait for user input after execution , Press enter and exit :

#!/usr/bin/python
# -*- coding: UTF-8 -*-
input(" Press down enter Key to exit , Any other key displays ...\n")

In the above code ,\n Implement line break . Once the user presses enter( enter ) Key to exit , Other key display .

11. Show multiple statements on the same line

Python You can use multiple statements on the same line , Use semicolons... Between statements (;) Division , Here is a simple example :

#!/usr/bin/python
import sys; x = 'ShowMeAI'; sys.stdout.write(x + '\n')

Execute the above code , The input result is :

$ python test.py
ShowMeAI

12.print Output

python3 in print The default output is line feed , If you want to implement no line wrapping, you need to add... At the end of the variable 「, end=''」.

#!/usr/bin/python
# -*- coding: UTF-8 -*-
x="a"
y="b"
# Line feed output
print(x)
print(y)
print('---------')
# Don't wrap output
print(x, end='')
print(y, end='')
# Don't wrap output
print(x, y, end='')

The execution result of the above example is :

a
b
---------
a b a b

13. Code block / Code group

Indent the same set of statements into a block of code , We call it code group .

image if、while、def and class Such compound statements , The first line starts with keywords , With a colon ( : ) end , One or more lines of code following this line form a code group .

We call the first and subsequent code groups a clause (clause).

The following example :

if expression :
suite
elif expression :
suite
else :
suite

Data and code download

The code for this tutorial series can be found in ShowMeAI Corresponding github Download , Can be local python Environment is running , You can visit google Your baby can also use google colab One click operation and interactive operation learning Oh !

This tutorial series covers Python The quick look-up table can be downloaded and obtained at the following address :

  • Python Quick reference table

Expand references

  • Python course —Python3 file
  • Python course - Liao Xuefeng's official website

ShowMeAI Recommended articles

  • python Introduce
  • python Installation and environment configuration
  • python Basic grammar
  • python Basic data type
  • python Operator
  • python Condition control and if sentence
  • python Loop statement
  • python while loop
  • python for loop
  • python break sentence
  • python continue sentence
  • python pass sentence
  • python String and operation
  • python list
  • python Tuples
  • python Dictionaries
  • python aggregate
  • python function
  • python Iterators and generators
  • python data structure
  • python modular
  • python File read and write
  • python File and directory operations
  • python Error and exception handling
  • python object-oriented programming
  • python Namespace and scope
  • python Time and date

ShowMeAI A series of tutorials are recommended

  • The illustration Python Programming : From introduction to mastery
  • Graphical data analysis : From introduction to mastery
  • The illustration AI Mathematical basis : From introduction to mastery
  • Illustrate big data technology : From introduction to mastery


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