15個有趣的Python腳本,讓你從入門到精通
Python因其可讀性和直接明了的語法而成為一種非常適合編程初學(xué)者的語言。初入Python后,想要提高你的編程技巧嗎?快來看看這里的腳本吧!本文介紹了15個有趣的Python腳本,讓你從入門到精通。
1. Hello, World!
所有程序員的經(jīng)典起點,這個腳本介紹了Python語法的基礎(chǔ)。
print("Hello, World!")
2. 簡易計算器
創(chuàng)建一個基本的計算器,執(zhí)行加法、減法、乘法和除法。
def calculator():
operation = input("選擇操作(+,-,*,/):")
num1 = float(input("輸入第一個數(shù)字:"))
num2 = float(input("輸入第二個數(shù)字:"))
if operation == '+':
print(f"{num1} + {num2} = {num1 + num2}")
elif operation == '-':
print(f"{num1} - {num2} = {num1 - num2}")
elif operation == '*':
print(f"{num1} * {num2} = {num1 * num2}")
elif operation == '/':
print(f"{num1} / {num2} = {num1 / num2}")
else:
print("無效操作")
calculator()
3. 猜數(shù)字
這個游戲隨機選擇一個1到100之間的數(shù)字,玩家必須猜出它。
from PIL import Image
import os
def batch_resiimport random
def guess_the_number():
number_to_guess = random.randint(1, 100)
guess = None
while guess != number_to_guess:
guess = int(input("猜一個1到100之間的數(shù)字:"))
if guess < number_to_guess:
print("太低了!")
elif guess > number_to_guess:
print("太高了!")
else:
print("恭喜你!你猜對了。")
guess_the_number()import random
def guess_the_number():
number_to_guess = random.randint(1, 100)
guess = None
while guess != number_to_guess:
guess = int(input("猜一個1到100之間的數(shù)字:"))
if guess < number_to_guess:
print("太低了!")
elif guess > number_to_guess:
print("太高了!")
else:
print("恭喜你!你猜對了。")
guess_the_number()ze(folder, width, height):
for filename in os.listdir(folder):
if filename.endswith(('.jpeg', '.jpg', '.png')):
img = Image.open(os.path.join(folder, filename))
img = img.resize((width, height))
img.save(os.path.join(folder, f"resized_{filename}"))
print(f'調(diào)整了 {filename} 的大小')
batch_resize('/path/to/images', 800, 600)
4. 石頭剪刀布
實現(xiàn)經(jīng)典的石頭、剪刀、布游戲。
import random
def rock_paper_scissors():
choices = ['rock', 'paper', 'scissors']
computer_choice = random.choice(choices)
user_choice = input("選擇石頭、剪刀或布:").lower()
if user_choice not in choices:
print("無效選擇")
return
print(f"計算機選擇了:{computer_choice}")
if user_choice == computer_choice:
print("平局!")
elif (user_choice == 'rock' and computer_choice == 'scissors') or \
(user_choice == 'scissors' and computer_choice == 'paper') or \
(user_choice == 'paper' and computer_choice == 'rock'):
print("你贏了!")
else:
print("你輸了!")
rock_paper_scissors()
5. 待辦事項列表
創(chuàng)建一個簡單的待辦事項列表應(yīng)用程序。
def to_do_list():
tasks = []
while True:
action = input("輸入 'add' 添加任務(wù),'remove' 刪除任務(wù),'view' 查看所有任務(wù),或 'quit' 退出:").lower()
if action == 'add':
task = input("輸入一個任務(wù):")
tasks.append(task)
elif action == 'remove':
task = input("輸入要刪除的任務(wù):")
if task in tasks:
tasks.remove(task)
else:
print("任務(wù)未找到")
elif action == 'view':
print("任務(wù):", tasks)
elif action == 'quit':
break
else:
print("無效操作")
to_do_list()
6. 基礎(chǔ)網(wǎng)頁抓取器
學(xué)習使用BeautifulSoup進行基礎(chǔ)的網(wǎng)頁抓取。
import requests
from bs4 import BeautifulSoup
def web_scraper():
url = 'http://example.com'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
print(soup.prettify())
web_scraper()
7. 天氣應(yīng)用
使用API獲取指定城市的天氣數(shù)據(jù)。
import requests
def weather_app():
api_key = 'your_api_key'
city = input("輸入城市名稱:")
url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}'
response = requests.get(url)
data = response.json()
if data['cod'] == 200:
main = data['main']
temperature = main['temp']
weather = data['weather'][0]['description']
print(f"溫度:{temperature}")
print(f"天氣:{weather}")
else:
print("城市未找到")
weather_app()
8. 填詞游戲生成器
創(chuàng)建一個有趣的填詞游戲,用戶通過輸入完成一個故事。
def mad_libs():
noun = input("輸入一個名詞:")
adjective = input("輸入一個形容詞:")
verb = input("輸入一個動詞:")
place = input("輸入一個地點:")
story = f"從前,有一個喜歡在{place}做{verb}的{adjective} {noun}。"
print(story)
mad_libs()
9. 斐波那契數(shù)列
生成到指定數(shù)字的斐波那契數(shù)列。
def fibonacci_sequence(n):
sequence = [0, 1]
while len(sequence) < n:
sequence.append(sequence[-1] + sequence[-2])
print(sequence)
fibonacci_sequence(10)
10. 密碼生成器
創(chuàng)建一個腳本,生成一個隨機的安全密碼。
import random
import string
def password_generator(length=12):
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for i in range(length))
print(password)
password_generator()
11. 吊死鬼游戲
創(chuàng)建一個經(jīng)典的吊死鬼游戲,玩家猜測字母以揭示隱藏的單詞。
import random
def hangman():
words = ['python', 'java', 'swift', 'javascript']
word = random.choice(words)
guessed_letters = set()
attempts = 6
while attempts > 0:
display_word = ''.join([letter if letter in guessed_letters else '_' for letter in word])
print(display_word)
if '_' not in display_word:
print("恭喜你!你猜對了單詞。")
break
guess = input("猜一個字母:").lower()
if guess in guessed_letters:
print("你已經(jīng)猜過那個字母了。")
elif guess in word:
guessed_letters.add(guess)
else:
attempts -= 1
print(f"猜錯了。你還有{attempts}次機會。")
if attempts == 0:
print(f"游戲結(jié)束!單詞是'{word}'。")
hangman()
12. 質(zhì)數(shù)檢查器
編寫一個腳本,檢查給定的數(shù)字是否為質(zhì)數(shù)。
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
number = int(input("輸入一個數(shù)字:"))
if is_prime(number):
print(f"{number} 是一個質(zhì)數(shù)。")
else:
print(f"{number} 不是一個質(zhì)數(shù)。")
13. 貨幣轉(zhuǎn)換器
創(chuàng)建一個簡單的貨幣轉(zhuǎn)換器,使用 API 獲取最新的匯率。
import requests
def currency_converter():
api_key = 'your_api_key'
base_currency = input("輸入基準貨幣(例如,USD):").upper()
target_currency = input("輸入目標貨幣(例如,EUR):").upper()
amount = float(input("輸入金額:"))
url = f'https://api.exchangerate-api.com/v4/latest/{base_currency}'
response = requests.get(url)
data = response.json()
if target_currency in data['rates']:
exchange_rate = data['rates'][target_currency]
converted_amount = amount * exchange_rate
print(f"{amount} {base_currency} 等于 {converted_amount:.2f} {target_currency}")
else:
print("貨幣不支持。")
currency_converter()
14. BMI計算器
創(chuàng)建一個腳本,根據(jù)用戶輸入計算身體質(zhì)量指數(shù)(BMI)。
def bmi_calculator():
height = float(input("輸入身高(米):"))
weight = float(input("輸入體重(千克):"))
bmi = weight / (height ** 2)
print(f"你的BMI是:{bmi:.2f}")
if bmi < 18.5:
print("你體重過輕。")
elif 18.5 <= bmi < 24.9:
print("你體重正常。")
elif 25 <= bmi < 29.9:
print("
15. 井字棋游戲
創(chuàng)建一個可供兩人游玩的井字棋游戲。
def print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 5)
def check_winner(board, player):
for row in board:
if all([cell == player for cell in row]):
return True
for col in range(3):
if all([board[row][col] == player for row in range(3)]):
return True
if all([board[i][i] == player for i in range(3)]) or all([board[i][2-i] == player for i in range(3)]):
return True
return False
def tic_tac_toe():
board = [[' ' for _ in range(3)] for _ in range(3)]
players = ['X', 'O']
turn = 0
for _ in range(9):
print_board(board)
player = players[turn % 2]
print(f"Player {player}'s turn")
row = int(input("Enter row (0, 1, 2): "))
col = int(input("Enter column (0, 1, 2): "))
if board[row][col] == ' ':
board[row][col] = player
if check_winner(board, player):
print_board(board)
print(f"Player {player} wins!")
return
turn += 1
else:
print("Cell already taken. Try again.")
print_board(board)
print("It's a tie!")
tic_tac_toe()
總結(jié)
這十五個腳本涵蓋了一系列基礎(chǔ)的Python概念,并為初學(xué)者提供了堅實的基礎(chǔ)。通過這些項目的實踐,新程序員可以建立起信心,并逐漸解決Python中更復(fù)雜的問題。