15个有趣的Python脚本,让你从入门到精通

开发 前端
这十五个脚本涵盖了一系列基础的Python概念,并为初学者提供了坚实的基础。通过这些项目的实践,新程序员可以建立起信心,并逐渐解决Python中更复杂的问题。

Python因其可读性和直接明了的语法而成为一种非常适合编程初学者的语言。初入Python后,想要提高你的编程技巧吗?快来看看这里的脚本吧!本文介绍了15个有趣的Python脚本,让你从入门到精通。

1. Hello, World!

所有程序员的经典起点,这个脚本介绍了Python语法的基础。

print("Hello, World!")

2. 简易计算器

创建一个基本的计算器,执行加法、减法、乘法和除法。

def calculator():
    operation = input("选择操作(+,-,*,/):")
    num1 = float(input("输入第一个数字:"))
    num2 = float(input("输入第二个数字:"))

    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. 猜数字

这个游戏随机选择一个1到100之间的数字,玩家必须猜出它。

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之间的数字:"))
        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之间的数字:"))
        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'调整了 {filename} 的大小')

batch_resize('/path/to/images', 800, 600)

4. 石头剪刀布

实现经典的石头、剪刀、布游戏。

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. 待办事项列表

创建一个简单的待办事项列表应用程序。

def to_do_list():
    tasks = []

    while True:
        action = input("输入 'add' 添加任务,'remove' 删除任务,'view' 查看所有任务,或 'quit' 退出:").lower()
        if action == 'add':
            task = input("输入一个任务:")
            tasks.append(task)
        elif action == 'remove':
            task = input("输入要删除的任务:")
            if task in tasks:
                tasks.remove(task)
            else:
                print("任务未找到")
        elif action == 'view':
            print("任务:", tasks)
        elif action == 'quit':
            break
        else:
            print("无效操作")

to_do_list()

6.  基础网页抓取器

学习使用BeautifulSoup进行基础的网页抓取。

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. 天气应用

使用API获取指定城市的天气数据。

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. 填词游戏生成器

创建一个有趣的填词游戏,用户通过输入完成一个故事。

def mad_libs():
    noun = input("输入一个名词:")
    adjective = input("输入一个形容词:")
    verb = input("输入一个动词:")
    place = input("输入一个地点:")

    story = f"从前,有一个喜欢在{place}做{verb}的{adjective} {noun}。"
    print(story)

mad_libs()

9. 斐波那契数列

生成到指定数字的斐波那契数列。

def fibonacci_sequence(n):
    sequence = [0, 1]
    while len(sequence) < n:
        sequence.append(sequence[-1] + sequence[-2])
    print(sequence)
fibonacci_sequence(10)

10. 密码生成器

创建一个脚本,生成一个随机的安全密码。

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. 吊死鬼游戏

创建一个经典的吊死鬼游戏,玩家猜测字母以揭示隐藏的单词。

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("你已经猜过那个字母了。")
        elif guess in word:
            guessed_letters.add(guess)
        else:
            attempts -= 1
            print(f"猜错了。你还有{attempts}次机会。")
    
    if attempts == 0:
        print(f"游戏结束!单词是'{word}'。")

hangman()

12. 质数检查器

编写一个脚本,检查给定的数字是否为质数。

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("输入一个数字:"))
if is_prime(number):
    print(f"{number} 是一个质数。")
else:
    print(f"{number} 不是一个质数。")

13. 货币转换器

创建一个简单的货币转换器,使用 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计算器

创建一个脚本,根据用户输入计算身体质量指数(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. 井字棋游戏

创建一个可供两人游玩的井字棋游戏。

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()

总结

这十五个脚本涵盖了一系列基础的Python概念,并为初学者提供了坚实的基础。通过这些项目的实践,新程序员可以建立起信心,并逐渐解决Python中更复杂的问题。

责任编辑:武晓燕 来源: Java学研大本营
相关推荐

2024-02-26 08:52:20

Python传递函数参数参数传递类型

2011-08-31 11:17:17

2024-06-07 08:51:50

OpenPyXLPythonExcel文件

2010-02-06 15:31:18

ibmdwAndroid

2009-07-22 14:55:16

ibmdwAndroid

2017-05-09 08:48:44

机器学习

2016-12-08 22:39:40

Android

2022-06-10 08:17:52

HashMap链表红黑树

2012-02-29 00:49:06

Linux学习

2024-01-11 09:35:12

单元测试Python编程软件开发

2023-05-09 08:34:51

PythonWith语句

2022-10-10 23:19:02

Python脚本语言工具库

2010-11-08 10:20:18

2022-09-02 15:11:18

开发工具

2019-10-08 11:07:55

Python 开发编程语言

2023-09-26 22:26:15

Python代码

2015-03-17 09:34:57

PHP响应式网页设计网页设计建议

2011-10-26 20:47:36

ssh 安全

2009-03-19 13:36:53

SSH安全通道远程

2017-01-09 09:34:03

Docker容器传统虚拟机
点赞
收藏

51CTO技术栈公众号