Python有着廣泛的應用場景,包括數據分析、人工智能、網絡爬蟲、Web應用等領域。Python 100個代碼示例是一個非常好的資源,它可以幫助初學者快速學習Python語言。本文將從多個方面詳細闡述這100個代碼示例,並給出相應的代碼實例。
一、變量和數據類型
變量是Python程序中存儲數據的容器。Python提供了多種數據類型來表示不同類型的數據。
1、整數類型
x = 10
y = 20
print(x + y)
2、浮點數類型
x = 3.14
y = 2.0
print(x * y)
3、字符串類型
x = "Hello"
y = "World"
print(x + " " + y)
二、列表、元組和字典
列表、元組和字典是Python中常用的數據結構。
1、列表
list1 = [1, 2, 3, 4, 5]
list2 = ["apple", "orange", "banana"]
print(list1[0])
print(list2[1])
2、元組
tuple1 = (1, 2, 3, 4, 5)
tuple2 = ("apple", "orange", "banana")
print(tuple1[0])
print(tuple2[1])
3、字典
dict1 = {'name': 'Tom', 'age':18, 'gender': 'male'}
print(dict1['name'])
print(dict1.get('age'))
三、流程控制語句
流程控制語句用於控制程序的執行流程。
1、if語句
x = 10
if x > 5:
print("x > 5")
else:
print("x <= 5")
2、for循環語句
list1 = [1, 2, 3, 4, 5]
for i in list1:
print(i)
3、while循環語句
x = 1
while x < 10:
print(x)
x = x + 1
四、函數和模塊
函數允許我們將代碼組織成可重用的模塊。可以使用Python內置模塊,也可以自己創建模塊。
1、函數
def add(x, y):
return x + y
print(add(1, 2))
2、模塊
import math
print(math.pi)
五、文件操作
Python提供了多種方式來讀取和寫入文件。
1、文件讀取
with open('test.txt', 'r') as f:
for line in f:
print(line)
2、文件寫入
with open('test.txt', 'w') as f:
f.write('Hello World!')
以上就是Python 100個代碼示例的相關介紹,希望對初學者有所幫助。
原創文章,作者:PSNVZ,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/373455.html