活動地址: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.
程序的格式框架,paragraph format,是Python
語法的一部分,可以提高代碼的可讀性和可維護性.
Python語言采用嚴格的縮進來表示程序邏輯.也就是我們所說的PythonInclusion and Hierarchy Relationships Between Programs.General code does not require indentation,頂行編寫且不留空白.在if、while、for、def、class
After 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.
注釋是代碼中的輔助性文字,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執行程序的一部分.
注釋的作用:
# -*- coding: utf-8 -*-
# @File : demo.py
# @author: Flyme awei
# @email : [email protected]
# @Time : 2022/8/2 13:40
# 單行注釋
'''多行注釋'''
"""多行注釋"""
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,稱為標識符.
變量是保存和表示數據值的一種語法元素,變量的值是可以改變的,通過賦值運算符“=
”方式被修改.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)
保留字也稱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
為保留字,而true
is not a reserved word.
標識符可以簡單的理解為一個名字,主要用來標識變量、函數、類、模塊和其他對象的名稱.
標識符的命名規則
ISO-Latin(ISO-8859-1)
字符集中的A-Z
和a-z
name
和Name
是兩個不同的名字. 二進制是一套計數方法,每個位置上的數有 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碼表
ASCIICode table character interpretation
Python提供的3種數值類型:
整數類型:Consistent with integers in mathematics,包含正、負、0.An integer is binary、八進制、十進制、十六進制4種表示方式.
浮點數類型: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
的形式表示,存在實部和虛部.
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]
獲取字符串中從N
到M
(但不包含M
)consecutive substrings of.N
和M
All 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
產生或計算新數據值的代碼片段稱為表達式.similar to formulas in mathematics,Usually consists of data and operators.
對變量進行賦值的一行代碼被稱為賦值語句.在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.
PythonThe program will often use the function of the existing code to the current program,This process is called referencing.
Python語言中使用import
This 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()
”方式.
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.
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,可寫可不寫.
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.
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 onlyprint(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天:入門必備