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

The Python language basic syntax elements

編輯:Python

活動地址:CSDN21天學習挑戰賽

前言

上一節,我們學習【Python語言程序設計的基本方法】,Know what is a programming language,了解了Python語言的發展及特點,並進行Python開發環境的搭建以及Python集成開發環境PyCharm的安裝及模板設置.
本節我們將學習Python語言的基本語法元素.包括Python程序的格式框架,Syntax element name,Data types and statement elements and basic input and output functions.

文章目錄

  • 前言
  • Python語言基本語法元素
    • 一、程序的格式框架
      • 1.縮進
      • 2.注釋
      • 3.續行符
    • 二、語法元素的名稱
      • 1.變量
      • 2.保留字
      • 3.標識符
    • 三、數據類型
      • 1.二進制與字符編碼
      • 2.數值類型
      • 3.字符串類型
    • 四、程序的語句元素
      • 1.表達式
      • 2.賦值語句
      • 3.引用
      • 4.其他語句
    • 五、基本輸入輸出函數
      • 1.input( )函數
      • 2.eval( )函數
      • 3.print()函數
    • 學習知識點

Python語言基本語法元素

一、程序的格式框架

程序的格式框架,paragraph format,是Python語法的一部分,可以提高代碼的可讀性和可維護性.

1.縮進

Python語言采用嚴格的縮進來表示程序邏輯.也就是我們所說的PythonInclusion and Hierarchy Relationships Between Programs.General code does not require indentation,頂行編寫且不留空白.在if、while、for、def、classAfter the complete sentence where the reserved word is located, pass the English“:”After end and in line indentation,表明後續代碼與緊鄰無縮進語句的所屬關系.

縮進可以用Tab鍵實現,也可以用多個空格實現(一般是4個空格),但兩者不能混用.建議采用4個空格方式書寫代碼.

for i in range(1, 10):
for j in range(1, i+1):
print(i, '*', j, '=', i*j, end='\t')
print()

當程序執行時,產生了“unexpected indent”錯誤,Indicates that there is an indentation mismatch in the code.

2.注釋

注釋是代碼中的輔助性文字,will be ignored by the compiler or interpreter,不被計算機執行,一般用於程序員對代碼的說明.Python語言中使用“#”表示一行注釋的開始.Comments can be passed anywhere on a line“#”開始,The following line is treated as a comment,And before the content is stillPython執行程序的一部分.

注釋的作用:

  • 注釋一般用於在代碼中標明作者和版權信息
  • 解釋代碼原理和用途
  • Program debugging aids by commenting out a single line of code.
# -*- coding: utf-8 -*-
# @File : demo.py
# @author: Flyme awei 
# @email : [email protected]
# @Time : 2022/8/2 13:40
# 單行注釋
'''多行注釋'''
"""多行注釋"""

3.續行符

Python程序是逐行編寫的,There is no limit to the length of each line of code,But from a programmer's point of view,A single line of code is too long and not good for reading.At this time, you can use the continuation character to split a single line of code into multiple lines of expression.

PythonThe continuation character in is“\”.No spaces are allowed after the continuation character,The straight line after line continuation operator.

print("Cities in Yunnan have{}\n{}\n{}\n{}".format('昆明',\
'曲靖',\
'大理',\
'麗江'))

二、語法元素的名稱

PythonThe basic unit of language is the word,A small number of words isPython語言規定的,Is called a reserved word.Most words are user defined,A variable or function is formed through a naming process,Used to represent data or code,稱為標識符.

1.變量

變量是保存和表示數據值的一種語法元素,變量的值是可以改變的,通過賦值運算符“=”方式被修改.Python語言中,Variables can be named at any time、隨時賦值、隨時使用.

由三部分組成:

""" 標識: id 類型: type 值: value """

After multiple assignments, it will point to a new space

name = 'hello' # 第一次賦值
print(id(name)) # 標識
print(type(name)) # 類型
name = 'world' # 第二次賦值
print(name)

2.保留字

保留字也稱keyword關鍵字,Internally defined by the programming language and reserved for use,每種程序設計語言都有一套保留字,Reserved words are generally used to form the overall framework of a program,Python3.x中一共有35個保留字.

import keyword # Import the key module
print(keyword.kwlist) # 調用keyword模塊的kwlist方法

Python3.x中的35個保留字

and as assert async await break
class continue def del elif else
except False finally for from
global if import in is lambda None
nonlocal not or pass raise return
True try while with yield

PythonThere are a total of reserved words involved in the second-level exam22個.選學5個:None、finally、lambda、pass、with.
PythonReserved words in are also case sensitive.舉例:True為保留字,而trueis not a reserved word.

3.標識符

標識符可以簡單的理解為一個名字,主要用來標識變量、函數、類、模塊和其他對象的名稱.

標識符的命名規則

  • 字母、數字、下劃線
  • 不能以數字開頭
  • 不能是Python中的保留字
  • 只允許使用ISO-Latin(ISO-8859-1)字符集中的A-Za-z
  • Chinese allowed,但不建議
  • 注意:標識符對大小寫敏感,nameName是兩個不同的名字.

三、數據類型

1.二進制與字符編碼

二進制是一套計數方法,每個位置上的數有 2 種可能(0 - 1);二進制是計算機的執行語言,But this counting method existed long before the advent of computers.,can be traced back to ancient Egypt.在日常生活中,We are using decimal,每個位置上的數有 10 種可能(0 - 9).

早期的程序員爸爸為了讓計算機能夠認識我,將我能夠認識的符號和數字對應好,Then make a table calledASCII表,告訴計算機某種符號你應該使用哪個整數表示,A使用了8個位(置)才能裝得下我,在計算機中他們叫一個字節.

ASCII 碼使用指定的 7 位或 8 位二進制數組合來表示 128 或 256 種可能的字符.標准 ASCII 碼也叫基礎ASCII碼,使用 7 位二進制數來表示所有的大寫和小寫字母,數字 0 到 9、標點符號, 以及在美式英語中使用的特殊控制字符.其中:

0~31及127(共33個)是控制字符或通信專用字符(其余為可顯示字符),如控制符:LF(換行)、CR(回車)、FF(換頁)、DEL(刪除)、BS(退格)、BEL(振鈴)等;通信專用字符:SOH(文頭)、EOT(文尾)、ACK(確認)等;ASCII值為 8、9、10 和 13 分別轉換為退格、制表、換行和回車字符.它們並沒有特定的圖形顯示,但會依不同的應用程序,而對文本顯示有不同的影響.

32~126(共95個)是字符(32sp是空格),其中48~57為0到9十個阿拉伯數字;

65~90為26個大寫英文字母,97~122號為26個小寫英文字母,其余為一些標點符號、運算符號等.

同時還要注意,在標准ASCII中,其 最高位(b7) 用作奇偶校驗位.所謂奇偶校驗,是指在代碼傳送過程中用來檢驗是否出現錯誤的一種方法,一般分奇校驗和偶校驗兩種.奇校驗規定:正確的代碼一個字節中 1 的個數必須是奇數,若非奇數,則在最高位 b7 添1;偶校驗規定:正確的代碼一個字節中1的個數必須是偶數,若非偶數,則在最高位 b7 添1.

後128個稱為擴展ASCII碼,目前許多基於x86的系統都支持使用擴展(或“高”)ASCII.擴展 ASCII 碼允許將每個字符的第 8 位用於確定附加的 128 個特殊符號字符、外來語字母和圖形符號.

ASCII碼表

ASCII值控制字符ASCII值控制字符ASCII值控制字符ASCII值控制字符0NUT32(space)64@96、1SOH33!65A97a2STX34”66B98b3ETX35#67C99c4EOT36$68D100d5ENQ37%69E101e6ACK38&70F102f7BEL39,71G103g8BS40(72H104h9HT41)73I105i10LF42*74J106j11VT43+75K107k12FF44,76L108l13CR45-77M109m14SO46.78N110n15SI47/79O111o16DLE48080P112p17DCI49181Q113q18DC250282R114r19DC351383S115s20DC452484T116t21NAK53585U117u22SYN54686V118v23TB55787W119w24CAN56888X120x25EM57989Y121y26SUB58:90Z122z27ESC59;91[123{ 28FS60<92/124|29GS61=93]125}30RS62>94^126~31US63?95—127DEL

ASCIICode table character interpretation

NUL 空VT 垂直制表SYN 空轉同步SOH 標題開始FF 換頁鍵ETB 信息組傳送結束STX 正文開始CR 回車CAN 作廢ETX 正文結束SO 移位輸出EM 紙盡EOY 傳輸結束SI 移位輸入SUB 代替ENQ 請求DLE 空格ESC 換碼ACK 收到通知DC1 設備控制1FS 文字分隔符BEL 報警DC2 設備控制2GS 組分隔符BS 退一格DC3 設備控制3RS 記錄分隔符HT 水平制表符DC4 設備控制4US 單元分隔符LF 換行NAK 拒絕DEL 刪除

2.數值類型

Python提供的3種數值類型:
整數類型:Consistent with integers in mathematics,包含正、負、0.An integer is binary、八進制、十進制、十六進制4種表示方式.

進制基本數逢幾進一表示形式十進制0,1,2,3,4,5,6,7,8,910520二進制0,120b11010八進制0,1,2,3,4,5,6,780o520十六進制0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F160xAF12546

浮點數類型:Consistent with decimals in mathematics,沒有取值范圍限制,可正、可負.有兩種表示形式,One is in the form of a decimal point,The other is scientific notation.浮點數只有十進制形式.

復數:Consistent with complex numbers in mathematics,采用a+bj的形式表示,存在實部和虛部.

3.字符串類型

Computers often process textual information,Text information is represented in the program using the string type.在Python中Use one or more characters enclosed in single or double quotes to indicate示.單引號和雙引號的作用相同.

# 字符串類型 被稱為不可變的字符序列
print('我用python')
print("我用python")
print('''我用python''')
print(type('我用python'))
print(type("我用python"))
print(type('''我用python'''))

There are two numbering systems for character sequences:
正向遞增序號: 有效范圍為[0,N-1],其中Nis the number of characters in the string.The leftmost character sequence number is0,依次向右遞增,最右側字符序號為N-1.

反向遞減序號:有效范圍為[-1,-N],其中Nis the number of characters in the string.The rightmost character sequence is the same as-1,依次向左遞減,The leftmost character sequence number is-N.

Both indexes can be used at the same time,The following code is an index to a single character.

s = 'hello word'
print(s[0]) # h
print(s[-10]) # h

還可以采用[N:M]格式獲取字符串的子串,This operation is called a slice operation.[N:M]獲取字符串中從NM(但不包含M)consecutive substrings of.NMAll indicate the index number,可以混合使用正向遞增序號和反向遞減序號.

s = 'hello word'
print(s[0:5]) # hello
print(s[0:-5]) # hello

通過Python默認提供的len()函數獲取字符串的長度,The length of a Chinese character and an English character are recorded as1.

print(len(s)) # 10

四、程序的語句元素

1.表達式

產生或計算新數據值的代碼片段稱為表達式.similar to formulas in mathematics,Usually consists of data and operators.

2.賦值語句

對變量進行賦值的一行代碼被稱為賦值語句.在Python中使用一個“=”表示“賦值”,That is, assign the result value of the expression on the right side of the equal sign to the variable on the left side.
The basic assignment statement syntax
變量 = 表達式


Synchronous assignment statements is through an assignment at the same time for multiple variables.
Syntax of Synchronized Assignment Statement:

變量1,變量2,......變量N=表達式1,表達式2,......,表達式N

Synchronous assignment application is swap the value of a variable.i.e. swap the values ​​of two variables.

3.引用

PythonThe program will often use the function of the existing code to the current program,This process is called referencing.

Python語言中使用importThis reserved word refers to a function library outside the current program.
import <功能庫名稱>
Use after referencing the function library 功能庫.函數名()The way to call the basic function,This method is called“A.B()”方式.

4.其他語句

In addition to the assignment statement,PythonThere are also branch statements and loop statements.Briefly introduce the use of,Explain in detail later.

分支語句:Select the program execution path according to the judgment condition.Usually contains a single branch structure、雙分支結構和多分支結構.
single branch syntax:

if 條件:
語句塊

任何能夠產生True或False的語句都可以作為條件,當條件為True時,execute the contents of the statement block.

Two-branch grammar structure:

if 條件:
語句塊1
else:
語句塊2

當條件為True時,執行語句塊1,當條件為False時,執行語句塊2.其中if...else 都是保留字.

循環結Structure and branch structure are program control statements,Its function is to determine whether a program is executed one or more times according to the judgment condition.

Conditional loop syntax:

while 條件:
語句塊1
語句塊2

當條件為True時,執行語句塊1,然後再次判斷條件,當條件為False時,退出循環,執行語句塊2.


五、基本輸入輸出函數

1.input( )函數

input()The function is to get a line of input from the user from the console,無論用戶輸入什麼內容,input()Functions all return as string type.input()函數可以包含一些提示性文字,用來提示用戶.

input語法格式:
變量=input('提示性文字')
Whether the user enters numbers or characters,input()函數統一按照字符串類型輸出,To subsequent operation user input,Need to specify a variable to store the input.

input()Hint text for functions is not required,可寫可不寫.

2.eval( )函數

eval(s)函數將去掉字符串s最外側的引號,並按照Python語句方式執行去掉引號後的字符內容.

eavl語法格式:
變量 = eval(字符串)

The variable is used to save the memory for the stringPython運算的結果.

eval()function strips the string’1.2’最外側的引號,結果賦值給a,所以a的類型為float類型.eval()function strips the string’1.2+3.4’最外側的引號,As to its contentsPython語句進行運算,運算的結果為4.6,保存到變量a中,所以a的類型是float類型.

eval()函數處理字符串’python’時,The quotation marks on both sides of the string to remove,Python語句將其解釋為一個變量,Due to the variable defined in before you have,So the interpreter reports an error.如果定義變量python並賦值為123,There is no problem when running this statement again,如果輸出為123.

eval()函數經常和input()函數一起使用,用來獲取用戶輸入的數字.

eval()input()Syntax used with functions:
變量=eval(input(提示性文字))q

用戶輸入的數字、包括小數和負數,input()解析為字符串,再由eval()remove string quotes,will be directly parsed as a number and saved to a variable.

3.print()函數

print()函數用於輸出運算結果.

def print(self, *args, sep=' ', end='\n', file=None): # known special case of print
""" print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream. """
pass

sep=' '分隔符,默認為一個空格
end='\n'結束符,end with newline by default

print()函數的三種用法:

1.For output string or single variable only
print(To the output string or a variable)

對於字符串,print()After the function is output, the quotation marks on both sides will be dropped,對於其它類型,則會直接輸出.

print()When the output string representation,Strings are expressed in single quotes.在[]Strings in double quotes are used,但是在被print()When the function prints the output,The output is in single quotes.

2.for outputting one or more variables ,The variables after output are separated by a space.
print(變量1,變量2,......,變量N)

3.Used to mix output strings with variable values,where the output string template is used{}表示一個槽位,Each slot corresponds to.format()中的一個變量.
print(輸出字符串模板.format(變量1,變量2,......,變量N))

‘整數{}和整數{}的差是:{}’The template is the output string,That is, the style of the mixed string output,大括號{}表示一個槽位,The content in parentheses is followed by theformat()方法中的參數按順序填充.

學習知識點

100天精通Python(基礎篇)——第2天:入門必備


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