一、變數和數據類型
Python的變數是動態類型的,不需要預先聲明變數的類型,只需要為變數分配一個值即可。Python的基本數據類型包括整數、浮點數、字元串、布爾值和空值(None)。
Python中的變數名不需要像其他語言一樣提前聲明,命名時需要遵循一定規則:變數名只能由字母、數字和下劃線組成,不能以數字開頭,不能使用關鍵字。
Python中的變數賦值是指將一個變數名與一個對象關聯起來。例如:
<pre> a = 10 # a是整數類型 b = 3.14 # b是浮點數類型 c = 'hello' # c是字元串類型 d = True # d是布爾類型 e = None # e是空值類型 </pre>
要判斷一個變數的數據類型,可以使用type()函數:
<pre> print(type(a)) # <class 'int'> print(type(b)) # <class 'float'> print(type(c)) # <class 'str'> print(type(d)) # <class 'bool'> print(type(e)) # <class 'NoneType'> </pre>
二、條件語句
Python中的條件語句包括if語句、elif語句和else語句。條件語句用於根據不同的條件執行不同的代碼塊。例如:
<pre> a = 10 if a > 0: print('a是正數') elif a == 0: print('a是零') else: print('a是負數') </pre>
在Python中,if語句、elif語句和else語句的代碼塊必須縮進,一般縮進4個空格。
三、循環語句
Python中的循環語句包括for循環和while循環。for循環通常用於遍歷序列(如列表、元組、字元串等),while循環通常用於在滿足一定條件下不斷重複某個代碼塊。
例如,使用for循環列印一個列表:
<pre> fruits = ['apple', 'banana', 'orange'] for fruit in fruits: print(fruit) </pre>
使用while循環實現1到10的累加求和:
<pre> i = 1 sum = 0 while i <= 10: sum += i i += 1 print(sum) </pre>
四、函數
Python中的函數使用def關鍵字定義,在函數名稱後面加上括弧並在括弧中指定參數,然後在冒號後面編寫函數代碼塊。
例如,編寫一個求和函數:
<pre> def add(x, y): return x + y print(add(1, 2)) # 輸出3 </pre>
函數參數可以是必需參數、關鍵字參數、默認參數和可變參數。例如,定義帶有默認值的參數:
<pre> def greeting(name, msg='Hello!'): print(name + ', ' + msg) greeting('Tom') # 輸出Tom, Hello! greeting('Kate', 'Good morning!') # 輸出Kate, Good morning! </pre>
五、面向對象
Python是一種面向對象的編程語言,支持封裝、繼承和多態。面向對象編程把數據和操作數據的函數放在一起,進行組合,形成一個可以復用的代碼。
例如,定義一個Person類:
<pre> class Person: def __init__(self, name, age): self.name = name self.age = age def say_hello(self): print('My name is ' + self.name + ', and I am ' + str(self.age) + ' years old.') p = Person('Tom', 20) p.say_hello() # 輸出My name is Tom, and I am 20 years old. </pre>
通過繼承可以擴展一個類,並使新類繼承父類的屬性和方法。
例如,定義一個Student類繼承自Person類:
<pre> class Student(Person): def __init__(self, name, age, grade): super().__init__(name, age) self.grade = grade def say_hello(self): print('My name is ' + self.name + ', and I am a student in grade ' + str(self.grade)) s = Student('Kate', 18, 12) s.say_hello() # 輸出My name is Kate, and I am a student in grade 12 </pre>
六、文件處理
Python可以讀取和寫入各種類型的文件,如文本文件、CSV文件和JSON文件等。
例如,讀取一個文本文件:
<pre> with open('data.txt') as f: data = f.read() print(data) </pre>
要寫入一個文本文件,在打開文件時需指定寫入模式(例如’w’),並使用write()函數寫入數據:
<pre> with open('data.txt', 'w') as f: f.write('Hello, world!') </pre>
七、常用模塊
Python有很多內置模塊和第三方模塊,可以擴展Python的功能。例如:
datetime模塊可以用來處理日期和時間。例如,獲取當前時間並格式化輸出:
<pre> import datetime now = datetime.datetime.now() print(now.strftime('%Y-%m-%d %H:%M:%S')) </pre>
random模塊可以用來生成隨機數。例如,生成一個1到10之間的隨機整數:
<pre> import random print(random.randint(1, 10)) </pre>
urllib模塊可以用來發送HTTP請求。例如,發送一個GET請求並獲取返回結果:
<pre> import urllib.request response = urllib.request.urlopen('https://www.baidu.com') print(response.read()) </pre>
八、總結
Python是一種簡單易學、功能強大的編程語言,廣泛應用於Web開發、數據科學、人工智慧等領域。針對Python面試的問題,本文分別介紹了變數和數據類型、條件語句、循環語句、函數、面向對象、文件處理和常用模塊等方面的知識點。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/240643.html