包含编程资料、学习路线图、源代码、软件安装包等!【[点击这里] 】!
今天和大家分享几个Python实用脚本,从“Hello, World!”到小游戏,循序渐进,带你入门Python的世界。
1. Hello, World!:编程世界的敲门砖
每个程序员的第一个程序几乎都是“Hello, World!”,它象征着你正式踏入了编程的世界。就像学习任何一门外语,第一句话都是“你好”一样,这是开启新征程的第一步。
print ( "Hello, World!" )
这段代码非常简单,print()函数的作用就是在屏幕上显示括号里的内容。就像你在微信上发送消息一样,你输入的内容会显示在对方的屏幕上。
2. 简易计算器:让Python帮你算算数
生活中我们经常需要进行一些简单的计算,Python可以轻松地扮演计算器的角色。
num1 = float ( input ( "请输入第一个数字:" ) )
num2 = float ( input ( "请输入第二个数字:" ) )
operator = input ( "请输入运算符(+、-、*、/):" )
if operator == "+" :
result = num1 + num2
elif operator == "-" :
result = num1 - num2
elif operator == "*" :
result = num1 * num2
elif operator == "/" :
if num2 == 0 :
print ( "除数不能为0" )
else :
result = num1 / num2
else :
print ( "无效的运算符" )
if "result" in locals ( ) :
print ( "结果:" , result)
这个简易计算器可以进行加减乘除运算。input()函数用于获取用户的输入,就像你在ATM机上输入密码一样。if-elif-else语句用于判断不同的运算符,就像你在选择外卖平台上的不同菜品一样。
3. 猜数字:和Python玩个游戏
让我们来玩一个猜数字的游戏,让Python随机生成一个数字,你来猜猜看。
import random
number = random. randint( 1 , 100 )
guess = 0
while guess != number:
guess = int ( input ( "猜一个1到100之间的数字:" ) )
if guess < number:
print ( "太小了,再试试!" )
elif guess > number:
print ( "太大了,再试试!" )
else :
print ( "恭喜你,猜对了!" )
random.randint(1, 100)会生成一个1到100之间的随机整数,就像抽奖一样,你不知道会抽到哪个数字。while循环会一直运行,直到你猜对为止,就像玩游戏一样,直到你通关为止。
4. 石头剪刀布:经典游戏Python版
石头剪刀布,这个经典的游戏也可以用Python来实现。
import random
choices = [ "石头" , "剪刀" , "布" ]
computer_choice = random. choice( choices)
user_choice = input ( "请输入你的选择(石头、剪刀、布):" )
print ( "你的选择:" , user_choice)
print ( "计算机的选择:" , computer_choice)
这里使用了random.choice()函数,让计算机从列表中随机选择一个选项,就像你让朋友帮你随机选择一个餐厅一样。
5. 待办事项列表:让Python帮你管理任务
todo_list = [ ]
while True :
action = input ( "请输入操作(添加、查看、退出):" )
if action == "添加" :
item = input ( "请输入待办事项:" )
todo_list. append( item)
elif action == "查看" :
for item in todo_list:
print ( item)
elif action == "退出" :
break
else :
print ( "无效的操作" )
6. 基础网页抓取器:获取网络信息
想象一下,你想要收集某个网站上的所有商品价格,或者你想自动下载一些图片,这时候就需要用到网页抓取器。
import requests
from bs4 import BeautifulSoup
url = "https://www.example.com"
response = requests. get( url)
soup = BeautifulSoup( response. content, "html.parser" )
title = soup. title. string
print ( "网页标题:" , title)
links = soup. find_all( "a" )
for link in links:
print ( link. get( "href" ) )
这个脚本使用了requests库来获取网页内容,就像你在浏览器中输入网址访问网页一样。 BeautifulSoup库则像一个过滤器,帮助你从杂乱的网页代码中提取你需要的信息,就像你从一堆文件中找到你想要的那一份一样。
7. 天气应用:实时掌握天气信息
想知道今天的天气怎么样?Python可以帮你实现一个简单的天气应用。
import requests
city = input ( "请输入城市名称:" )
api_key = "YOUR_API_KEY"
url = f"http://api.weatherapi.com/v1/current.json?key= { api_key} &q= { city} "
response = requests. get( url)
weather_data = response. json( )
if "current" in weather_data:
temperature = weather_data[ "current" ] [ "temp_c" ]
condition = weather_data[ "current" ] [ "condition" ] [ "text" ]
print ( f" { city} 当前温度: { temperature} ℃,天气状况: { condition} " )
else :
print ( "获取天气信息失败" )
这个简化的例子使用了天气API来获取天气数据,就像你打电话给气象台询问天气一样。你需要注册一个天气API并获取API密钥才能使用。
8. 疯狂填词游戏生成器:发挥你的创意
想玩一个填词游戏?Python可以帮你生成游戏模板。
import random
words = [ "apple" , "banana" , "orange" ]
template = "我喜欢吃____,也喜欢吃____,但更喜欢吃____。"
blanks = template. count( "____" )
selected_words = random. sample( words, blanks)
for word in selected_words:
template = template. replace( "____" , word, 1 )
print ( template)
这个脚本随机选择一些单词填入模板中,就像你玩填字游戏一样,你需要选择合适的词语填入空格。
9. 斐波那契数列:探索数学之美
斐波那契数列是一个经典的数学数列,每一项都是前两项的和。
def fibonacci ( n) :
if n <= 1 :
return n
else :
return fibonacci( n- 1 ) + fibonacci( n- 2 )
n = int ( input ( "请输入要计算的斐波那契数列项数:" ) )
result = fibonacci( n)
print ( f"第 { n} 项斐波那契数是: { result} " )
这个脚本使用了递归函数来计算斐波那契数列,就像你一步一步爬楼梯一样,每一步都依赖于前两步。
10. 密码生成器:守护你的账户安全
一个强密码是网络安全的第一道防线。Python可以帮助你生成随机的、难以破解的密码。
import random
import string
def generate_password ( length= 12 ) :
characters = string. ascii_letters + string. digits + string. punctuation
password = '' . join( random. choice( characters) for i in range ( length) )
return password
password = generate_password( )
print ( "生成的密码:" , password)
可以根据需要调整length参数来控制密码长度 这个脚本就像一个密码锁,它使用字母、数字和符号的组合生成随机密码,增加密码的复杂度,就像用不同的锁芯组合成一个更安全的锁一样.
11. 吊死鬼游戏:挑战你的词汇量
word = "apple"
guesses = [ ]
max_attempts = 6
while max_attempts > 0 :
masked_word = ""
for letter in word:
if letter in guesses:
masked_word += letter
else :
masked_word += "_"
print ( masked_word)
if masked_word == word:
print ( "恭喜你,你赢了!" )
break
guess = input ( "猜一个字母:" )
guesses. append( guess)
if guess not in word:
max_attempts -= 1
print ( "猜错了,你还有" , max_attempts, "次机会" )
if max_attempts == 0 :
print ( "你输了,单词是:" , word)
就像猜谜语一样,你根据提示逐步猜测单词,每次猜错都会减少你的机会。
12. 质数检查器:探索数学奥秘
def is_prime ( num) :
if num <= 1 :
return False
for i in range ( 2 , int ( num** 0.5 ) + 1 ) :
if num % i == 0 :
return False
return True
num = int ( input ( "请输入一个数字:" ) )
if is_prime( num) :
print ( num, "是质数" )
else :
print ( num, "不是质数" )
就像筛子一样,这个脚本会检查一个数字是否能被其他数字整除,如果不是,则它是质数。
13. 货币转换器:方便你的旅行
import requests
def convert_currency ( amount, from_currency, to_currency) :
api_key = "YOUR_API_KEY"
url = f"https://api.exchangerate-api.com/v4/latest/ { from_currency} "
response = requests. get( url)
data = response. json( )
if "rates" in data and to_currency in data[ "rates" ] :
rate = data[ "rates" ] [ to_currency]
converted_amount = amount * rate
return converted_amount
else :
return None
amount = float ( input ( "请输入金额:" ) )
from_currency = input ( "请输入原始货币(例如 USD):" ) . upper( )
to_currency = input ( "请输入目标货币(例如 CNY):" ) . upper( )
converted_amount = convert_currency( amount, from_currency, to_currency)
if converted_amount:
print ( f" { amount} { from_currency} 等于 { converted_amount} { to_currency} " )
else :
print ( "无法转换货币" )
这个简化的例子使用汇率API来获取最新的汇率信息,就像你在银行兑换货币一样。
14. BMI计算器:关注你的健康
height = float ( input ( "请输入身高(米):" ) )
weight = float ( input ( "请输入体重(公斤):" ) )
bmi = weight / ( height ** 2 )
print ( "你的BMI是:" , bmi)
就像用尺子测量身高一样,这个脚本根据你的身高和体重计算你的BMI。
15. 定时发送邮件:
这个脚本可以定时自动发送邮件。例如,你可以用它来定时发送生日祝福、提醒事项,或者发送定期报告等。 它使用了smtplib库来发送邮件,schedule库来定时执行任务。
import smtplib
from email. mime. text import MIMEText
import schedule
import time
def send_email ( ) :
"""发送邮件的函数"""
msg_from = '你的邮箱地址'
passwd = '你的邮箱密码'
msg_to = '接收方邮箱地址'
subject = "定时邮件测试"
content = "这是一封定时发送的邮件。"
msg = MIMEText( content)
msg[ 'Subject' ] = subject
msg[ 'From' ] = msg_from
msg[ 'To' ] = msg_to
try :
s = smtplib. SMTP_SSL( "smtp.qq.com" , 465 )
s. login( msg_from, passwd)
s. sendmail( msg_from, msg_to, msg. as_string( ) )
print ( "邮件发送成功" )
except Exception as e:
print ( "邮件发送失败:" , e)
finally :
s. quit( )
schedule. every( ) . day. at( "10:00" ) . do( send_email)
while True :
schedule. run_pending( )
time. sleep( 1 )
16. 自动化文件整理:
这个脚本可以自动整理指定文件夹中的文件,按照文件扩展名进行分类。 例如,它可以将图片、文档、视频等不同类型的文件分别移动到不同的文件夹中,保持你的文件 organized。 它使用了os库来操作文件和文件夹,shutil库来移动文件。
import os
import shutil
def organize_files ( source_folder, dest_folder) :
"""整理文件的函数"""
for filename in os. listdir( source_folder) :
source_path = os. path. join( source_folder, filename)
if os. path. isfile( source_path) :
ext = os. path. splitext( filename) [ 1 ] . lower( )
dest_path = os. path. join( dest_folder, ext[ 1 : ] )
os. makedirs( dest_path, exist_ok= True )
shutil. move( source_path, dest_path)
source_folder = "/path/to/your/source/folder"
dest_folder = "/path/to/your/destination/folder"
organize_files( source_folder, dest_folder)
17. 生成二维码:
这个脚本可以生成二维码图片。你可以将文本、网址、联系方式等信息编码到二维码中,方便用户扫描获取信息。 它使用qrcode库来生成二维码。
import qrcode
data = "https://www.example.com"
img = qrcode. make( data)
img. save( "qrcode.png" )
18. 图像处理 (调整大小):
这个脚本可以调整图片的大小。你可以指定新的宽度和高度,将图片缩放到你需要的尺寸。 它使用PIL库 (Pillow) 来处理图像。
import qrcode
data = "https://www.example.com"
img = qrcode. make( data)
img. save( "qrcode.png" )
19. 批量重命名文件:
这个脚本可以批量重命名指定文件夹中的文件,例如添加序号、修改扩展名等。 这在处理大量文件时非常有用,例如批量重命名照片、文档等。
import os
def batch_rename ( folder_path, new_name_prefix= "file_" ) :
"""批量重命名文件的函数"""
i = 1
for filename in os. listdir( folder_path) :
old_path = os. path. join( folder_path, filename)
if os. path. isfile( old_path) :
ext = os. path. splitext( filename) [ 1 ]
new_name = f" { new_name_prefix} { i} { ext} "
new_path = os. path. join( folder_path, new_name)
os. rename( old_path, new_path)
i += 1
print ( f"已将 { filename} 重命名为 { new_name} " )
folder_path = "/path/to/your/folder"
batch_rename( folder_path)
20. 简单的网页服务器:
这个脚本可以创建一个简单的网页服务器,让你可以通过浏览器访问本地电脑上的文件。 这在开发和测试网页时非常有用。
import http. server
import socketserver
PORT = 8000
Handler = http. server. SimpleHTTPRequestHandler
with socketserver. TCPServer( ( "" , PORT) , Handler) as httpd:
print ( "serving at port" , PORT)
httpd. serve_forever( )
21. 下载YouTube视频:
这个脚本可以下载YouTube视频,方便你离线观看。
from pytube import YouTube
def download_youtube_video ( url, resolution= 'highest' ) :
"""下载YouTube视频的函数"""
try :
yt = YouTube( url)
stream = yt. streams. filter ( progressive= True , file_extension= 'mp4' ) . order_by( 'resolution' ) . desc( ) . first( )
if not stream:
print ( "找不到合适的视频流" )
return
print ( f"正在下载: { yt. title} " )
stream. download( )
print ( "下载完成!" )
except Exception as e:
print ( f"下载失败: { e} " )
video_url = "https://www.youtube.com/watch?v=你的视频ID"
download_youtube_video( video_url)
希望今天的分享能让你感受到Python的趣味性和实用性。继续探索,你将发现更多Python的精彩应用!
总结
最后希望你编程学习上不急不躁,按照计划有条不紊推进,把任何一件事做到极致,都是不容易的,加油,努力!相信自己!
文末福利
最后这里免费分享给大家一份Python全套学习资料,希望能帮到那些不满现状,想提升自己却又没有方向的朋友,也可以和我一起来学习交流呀。
包含编程资料、学习路线图、源代码、软件安装包等!【[点击这里] 】领取!
① Python所有方向的学习路线图,清楚各个方向要学什么东西 ② 100多节Python课程视频,涵盖必备基础、爬虫和数据分析 ③ 100多个Python实战案例,学习不再是只会理论 ④ 华为出品独家Python漫画教程,手机也能学习
可以扫描下方二维码领取【保证100%免费 】