新手学编程学的没有信心?来这里调节一下重获自信 ,现在小编就来说说关于小程序后台代码编写教程?下面内容希望能帮助到你,我们来一起看看吧!
小程序后台代码编写教程
新手学编程学的没有信心?来这里调节一下重获自信!
以下例子都很简单实用,非常适合初学者用来练习。大家也可尝试根据项目的目的及提示,自己构建解决方法,提高编程水平。
除此之外 ,小编还整理了更多适合小白的资料,有要的留下你的111
1、石头剪刀布游戏
目标:创建一个命令行游戏,游戏者可以在石头、剪刀和布之间进行选择,与计算机PK。如果游戏者赢了,得分就会增加,直到结束游戏时,最终的分数会展示给游戏者。
提示:接收游戏者的选择,并且与计算机的选择进行比较。计算机的选择是从选择列表中随机选取的。如果游戏者获胜,则增加1分。
import random
choices = ["Rock", "Paper", "Scissors"]
computer = random.choice(choices)
player = False
cpu_score = 0
player_score = 0
while True:
player = input("Rock, Paper or Scissors?").capitalize()
# 判断游戏者和电脑的选择
if player == computer:
print("Tie!")
elif player == "Rock":
if computer == "Paper":
print("You lose!", computer, "covers", player)
cpu_score =1
else:
print("You win!", player, "smashes", computer)
player_score =1
elif player == "Paper":
if computer == "Scissors":
print("You lose!", computer, "cut", player)
cpu_score =1
else:
print("You win!", player, "covers", computer)
player_score =1
elif player == "Scissors":
if computer == "Rock":
print("You lose...", computer, "smashes", player)
cpu_score =1
else:
print("You win!", player, "cut", computer)
player_score =1
elif player=='E':
print("Final Scores:")
print(f"CPU:{cpu_score}")
print(f"Plaer:{player_score}")
break
else:
print("That's not a valid play. Check your spelling!")
computer = random.choice(choices)
目的:编写一个Python脚本,可以使用这个脚本发送电子邮件。
提示:Email库可用于发送电子邮件。
import smtplib
from email.message import emailMessage
email = EmailMessage()
email['from'] = 'xyz name'
email['to'] = 'xyz id'
email['subject'] = 'xyz subject'
email.set_content("Xyz content of email")
with smtlib.SMTP(host='smtp.gmail.com',port=587)as smtp:
## sending request to server
smtp.ehlo()
smtp.starttls()
smtp.login("email_id","Password")
smtp.send_message(email)
print("email send")
目的:编写一个创建闹钟的Python脚本。
提示:你可以使用date-time模块创建闹钟,以及playsound库播放声音。
from datetime import datetime
from playsound import playsound
alarm_time = input("Enter the time of alarm to be set:HH:MM:SS\n")
alarm_hour=alarm_time[0:2]
alarm_minute=alarm_time[3:5]
alarm_seconds=alarm_time[6:8]
alarm_period = alarm_time[9:11].upper()
print("Setting up alarm..")
while True:
now = datetime.now()
current_hour = now.strftime("%I")
current_minute = now.strftime("%M")
current_seconds = now.strftime("%S")
current_period = now.strftime("%p")
if(alarm_period==current_period):
if(alarm_hour==current_hour):
if(alarm_minute==current_minute):
if(alarm_seconds==current_seconds):
print("Wake Up!")
playsound('audio.mp3') ## download the alarm sound from link
break
目的:创建一个简单的命令行hangman游戏。
提示:创建一个密码词的列表并随机选择一个单词。现在将每个单词用下划线“_”表示,给用户提供猜单词的机会,如果用户猜对了单词,则将“_”用单词替换。
import time
import random
name = input("What is your name? ")
print ("Hello, " name, "Time to play hangman!")
time.sleep(1)
print ("Start guessing...\n")
time.sleep(0.5)
## A List Of Secret Words
words = ['python','programming','treasure','creative','medium','horror']
word = random.choice(words)
guesses = ''
turns = 5
while turns > 0:
failed = 0
for char in word:
if char in guesses:
print (char,end="")
else:
print ("_",end=""),
failed = 1
if failed == 0:
print ("\nYou won")
break
guess = input("\nguess a character:")
guesses = guess
if guess not in word:
turns -= 1
print("\nWrong")
print("\nYou have", turns, 'more guesses')
if turns == 0:
print ("\nYou Lose")
目的:编写一个猜大小的Python小游戏。
提示:你可以使用random随机生成数字。
# 猜数游戏人机对战
import random
target=random.randint(1,100)
count=0
while True:
guess=eval(input('请输入一个猜测的整数(1至100)'))
count =1
if guess>target:
print('猜大了')
elif guess<target:
print('猜小了')
else:
print('猜对了')
break
print('此轮的猜测次数是:',count)
目的:编写一个数学计算的Python小游戏。
提示:你可以使用random随机生成数字相互之间加减,答对了即可进入下一关。
from random import randint
level=0 #0级开始
while level<10: #当级别小于10级时
a=randint(0,100) #随机生成两位数整数
b=randint(0,100)
c=input(f"{a} {b}=")
c=int(c)
if c==a b: #计算结果正确
level =1 #级别加1
print(f"答对啦!现在等级是{level}级,达到10级就胜利了!")
else: #计算结果错误
level-=1
print(f"答错啦!现在等级是{level},达到10级就胜利了!再接再厉!")
print(f"成功达到10级!挑战成功!棒棒哒!")
#减法闯关小游戏,对上面程序进行改造,需要注意进行减法前需对两个数字进行比较,以免出现负数。
from random import randint
level=0 #0级开始
while level<10: #当级别小于10级时
a=randint(0,100) #随机生成两位数整数
b=randint(0,100)
if a>=b:
c=input(f"{a}-{b}=")
c=int(c)
if c==a b: #计算结果正确
level =1 #级别加1
print(f"答对啦!现在等级是{level}级,达到10级就胜利了!")
else: #计算结果错误
level-=1
print(f"答错啦!现在等级是{level},达到10级就胜利了!再接再厉!")
print(f"成功达到10级!挑战成功!棒棒哒!")
目的:编写一个英语单词填填填的Python小游戏。
提示:你可以使用random随机生成一个英语单词,答对了即可!
import random
# 存放单词的列表(可以自己填写需要背诵的单词)
words = ["print", "int", "str", "len", "input", "format", "if","for","def"]
#初始化信息↓↓↓↓↓↓↓
def init():
# 声明三个全局变量
global word
global tips
global ranList
#随机获取单词列表里的一个单词
word = list(words[random.randint(0, len(words) - 1)])
#随机数列表,存放着与单词长度一致的随机数(不重复)
ranList = random.sample(range(0, len(word)), len(word))
#存放提示信息
tips = list()
#初始化提示信息
#存放跟单词长度一致的下划线
for i in range(len(word)):
tips.append("_")
#随机提示两个字母
tips[ranList[0]] = word[ranList[0]]
tips[ranList[1]] = word[ranList[1]]
#函数部分↓↓↓↓↓
#展示菜单
def showMenu():
print("需要提示请输入'?'")
print("结束游戏请输入'quit!'")
#显示提示信息
def showtips():
for i in tips:
print(i, end=" ")
print()
#需要提示
def needTips(tipsSize):
#至少有两个未知字母
if tipsSize <= len(word)-3:
tips[ranList[tipsSize]] = word[ranList[tipsSize]]
tipsSize = 1
return tipsSize
else:
print("已没有提示!")
#主要运行函数↓↓↓↓↓↓
def run():
print("------python关键字版本-------")
init()
tipsSize = 2
showMenu()
while True:
print("提示:",end="")
showtips()
guessWord = input("猜一下这个单词:")
# ''.join(word)>把word列表的内容转换成字符串
if guessWord == ''.join(word):
print("恭喜你,猜对了!就是%s!"%(''.join(word)))
print("再猜一次")
init()
elif guessWord == '?':
tipsSize = needTips(tipsSize)
elif guessWord == 'quit!':
break
else:
print("猜错了!")
continue
run()
目的:编写一个Python脚本,可以检测图像中的人脸,并将所有的人脸保存在一个文件夹中。
提示:可以使用haar级联分类器对人脸进行检测。它返回的人脸坐标信息,可以保存在一个文件中。
import cv2
# Load the cascade
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# Read the input image
img = cv2.imread('images/img0.jpg')
# Convert into grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Detect faces
faces = face_cascade.detectMultiScale(gray, 1.3, 4)
# Draw rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x w, y h), (255, 0, 0), 2)
crop_face = img[y:y h, x:x w]
cv2.imwrite(str(w) str(h) '_faces.jpg', crop_face)
# Display the output
cv2.imshow('img', img)
cv2.imshow("imgcropped",crop_face)
cv2.waitKey()
目的:编写一个Python脚本,将用户按下的所有键保存在一个文本文件中。
提示:pynput是Python中的一个库,用于控制键盘和鼠标的移动,它也可以用于制作键盘记录器。简单地读取用户按
下的键,并在一定数量的键后将它们保存在一个文本文件中。
from pynput.keyboard import Key, Controller,Listener
import time
keyboard = Controller()
keys=[]
def on_press(key):
global keys
#keys.append(str(key).replace("'",""))
string = str(key).replace("'","")
keys.append(string)
main_string = "".join(keys)
print(main_string)
if len(main_string)>15:
with open('keys.txt', 'a') as f:
f.write(main_string)
keys= []
def on_release(key):
if key == Key.esc:
return False
with listener(on_press=on_press,on_release=on_release) as listener:
listener.join()
目的:编写一个Python脚本,使用API缩短给定的URL。
from __future__ import with_statement
import contextlib
try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
import sys
def make_tiny(url):
request_url = ('http://tinyurl.com/api-create.php?'
urlencode({'url':url}))
with contextlib.closing(urlopen(request_url)) as response:
return response.read().decode('utf-8')
def main():
for tinyurl in map(make_tiny, sys.argv[1:]):
print(tinyurl)
if __name__ == '__main__':
main()
-----------------------------OUTPUT------------------------
python url_shortener.py https://www.wikipedia.org/
https://tinyurl.com/buf3qt3
好啦!以上就是今天要给大家分享的内容,如果有需要可以收藏起来慢慢看哈~
边看的话也要试着自己敲代码啦!
还有,总结的一堆资料作为福利发给大家,一键三连,发发发!!!
,