python基礎(chǔ)代碼示例(可免費復(fù)制)
python基礎(chǔ)代碼在我們的工作中經(jīng)常性的會用到,今天sojson給大家?guī)硪恍┗A(chǔ)的python代碼來幫助你學(xué)習(xí)python編程,都是一些基礎(chǔ)的代碼片段,希望能給你學(xué)習(xí)python帶來幫助。
python基礎(chǔ)代碼示例如下
# 示例1: 打印Hello World
print("Hello, World!")
# 示例2: Python基礎(chǔ)數(shù)據(jù)類型
# 整數(shù)
a = 10
# 浮點數(shù)
b = 3.14
# 字符串
c = "Python"
# 布爾值
d = True
# 示例3: 列表操作
my_list = [1, 2, 3, 4, 5]
# 訪問列表
print(my_list[0]) # 輸出第一個元素
# 列表切片
print(my_list[1:3]) # 輸出第二個到第三個元素
# 列表追加
my_list.append(6)
# 列表長度
print(len(my_list))
# 示例4: 循環(huán)結(jié)構(gòu)
# for循環(huán)
for i in range(5):
print(i)
# while循環(huán)
j = 0
while j < 5:
print(j)
j += 1
# 示例5: 條件結(jié)構(gòu)
x = 10
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is equal to 5")
else:
print("x is less than 5")
# 示例6: 函數(shù)定義和調(diào)用
def greet(name):
return "Hello, " + name + "!"
print(greet("Alice"))
# 示例7: 類和對象
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def display_info(self):
print("This car is a", self.brand, self.model)
my_car = Car("Toyota", "Corolla")
my_car.display_info()
# 示例8: 文件操作
# 寫入文件
with open("example.txt", "w") as file:
file.write("This is an example file.")
# 讀取文件
with open("example.txt", "r") as file:
content = file.read()
print(content)
# 示例9: 異常處理
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("This is executed no matter what.")
# 示例10: 模塊導(dǎo)入
import math
print(math.sqrt(16)) # 輸出4.0總結(jié)
以上代碼提供了Python的基礎(chǔ)語法和操作,包括變量聲明、基本數(shù)據(jù)類型、控制流、函數(shù)、類、文件操作和異常處理。
版權(quán)所屬:SO JSON在線解析
原文地址:http://suancuo.cn/blog/494.html
轉(zhuǎn)載時必須以鏈接形式注明原始出處及本聲明。
如果本文對你有幫助,那么請你贊助我,讓我更有激情的寫下去,幫助更多的人。
