Python 基本命令及示例代碼(入門必備指南)
Python 基本命令詳解:入門必備指南
?? 引言
Python 是一種簡單易學、功能強大的編程語言,廣泛用于數(shù)據(jù)分析、Web 開發(fā)、人工智能、自動化腳本等領(lǐng)域。掌握 Python 的基本命令是入門的第一步。本篇文章將詳細介紹 Python 基本語法、常用命令及示例代碼,幫助你快速上手 Python 編程。
1. Python 環(huán)境安裝與運行
? 檢查 Python 版本
在終端(Mac/Linux)或命令提示符(Windows)中輸入:
python --version
或
python3 --version
如果 Python 未安裝,請前往 Python 官網(wǎng) 下載并安裝。
? 運行 Python 交互模式
輸入 python 或 python3 進入交互模式:
$ python
Python 3.10.0 (default, Oct 4 2021, 09:35:00)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello, Python!")
Hello, Python!按 Ctrl + D 退出交互模式。
? 運行 Python 腳本
創(chuàng)建 hello.py 文件:
print("Hello, Python!")在終端運行:
python hello.py
2. Python 基本語法
? 變量與數(shù)據(jù)類型
Python 是動態(tài)類型語言,不需要聲明變量類型:
name = "Alice" # 字符串 age = 25 # 整數(shù) height = 1.75 # 浮點數(shù) is_student = True # 布爾值
查看變量類型:
print(type(name)) # <class 'str'> print(type(age)) # <class 'int'>
? 基本輸入輸出
name = input("請輸入你的名字: ") # 用戶輸入
print("你好,", name) # 輸出? 字符串操作
text = "Hello, Python!"
print(text.upper()) # 轉(zhuǎn)大寫
print(text.lower()) # 轉(zhuǎn)小寫
print(text.replace("Python", "World")) # 替換
print(text[0:5]) # 字符串切片? 數(shù)字運算
a, b = 10, 3 print(a + b) # 加法 print(a - b) # 減法 print(a * b) # 乘法 print(a / b) # 除法 print(a // b) # 取整除 print(a % b) # 取余數(shù) print(a ** b) # 冪運算
3. 條件語句與循環(huán)
? 條件語句(if-else)
score = int(input("請輸入你的分數(shù): "))
if score >= 90:
print("優(yōu)秀")
elif score >= 60:
print("及格")
else:
print("不及格")? 循環(huán)(for 和 while)
# for 循環(huán)
for i in range(1, 6):
print(i, end=" ") # 輸出 1 2 3 4 5
print() # 換行
# while 循環(huán)
n = 5
while n > 0:
print(n, end=" ") # 輸出 5 4 3 2 1
n -= 14. 列表、元組、字典與集合
? 列表(list)
fruits = ["蘋果", "香蕉", "橙子"]
print(fruits[0]) # 訪問第一個元素
fruits.append("葡萄") # 添加元素
fruits.remove("香蕉") # 刪除元素
print(len(fruits)) # 列表長度? 元組(tuple)
colors = ("紅色", "藍色", "綠色")
print(colors[1]) # 訪問元素? 字典(dict)
person = {"name": "Alice", "age": 25, "city": "Beijing"}
print(person["name"]) # 訪問值
person["age"] = 26 # 修改值
person["gender"] = "Female" # 添加新鍵值對
del person["city"] # 刪除鍵值對? 集合(set)
numbers = {1, 2, 3, 4, 5}
numbers.add(6) # 添加元素
numbers.remove(3) # 刪除元素
print(numbers)5. 函數(shù)
? 定義與調(diào)用
def greet(name):
return f"Hello, {name}!"
print(greet("Alice")) # Hello, Alice!? 關(guān)鍵字參數(shù) & 默認參數(shù)
def introduce(name, age=18):
print(f"姓名: {name}, 年齡: {age}")
introduce("Tom") # 默認年齡 18
introduce("Jerry", 25) # 指定年齡 256. 文件操作
? 讀取文件
with open("example.txt", "r") as file:
content = file.read()
print(content)? 寫入文件
with open("example.txt", "w") as file:
file.write("Hello, Python 文件操作!")7. 異常處理
try:
num = int(input("輸入一個整數(shù): "))
result = 10 / num
except ZeroDivisionError:
print("錯誤: 不能除以 0")
except ValueError:
print("錯誤: 請輸入正確的數(shù)字")
else:
print("結(jié)果:", result)
finally:
print("程序結(jié)束")8. 模塊與庫
? 導入標準庫
import math print(math.sqrt(16)) # 計算平方根
? 安裝第三方庫
使用 pip 安裝:
pip install requests
使用示例:
import requests
response = requests.get("https://api.github.com")
print(response.status_code)9. 面向?qū)ο缶幊蹋∣OP)
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print(f"我是 {self.name},今年 {self.age} 歲")
p = Person("Alice", 25)
p.introduce() # 我是 Alice,今年 25 歲?? 結(jié)論
本篇文章介紹了 Python 的基本命令,包括變量、數(shù)據(jù)類型、條件語句、循環(huán)、函數(shù)、文件操作、異常處理、模塊與 OOP。
到此這篇關(guān)于Python 基本命令詳解:入門必備指南的文章就介紹到這了,更多相關(guān)Python 基本命令內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
anaconda3:conda not found報錯問題解決
這篇文章主要給大家介紹了關(guān)于anaconda3:conda not found報錯問題解決的相關(guān)資料,Anaconda指的是一個開源的Python發(fā)行版本,其包含了conda、Python等180多個科學包及其依賴項,需要的朋友可以參考下2023-10-10
python3 如何使用 goto 跳轉(zhuǎn)執(zhí)行到指定代碼行
這篇文章主要介紹了python3 使用goto跳轉(zhuǎn)執(zhí)行到指定代碼行的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-05-05
Pytorch數(shù)據(jù)拼接與拆分操作實現(xiàn)圖解
Python利用pyreadline模塊實現(xiàn)交互式命令行開發(fā)
Python?turtle.right與turtle.setheading的區(qū)別講述

