python练手小程序


1.生成200个指定长度的随机码


import random
import string

def rand_str(num,len=7):
    f = open('file.txt','w')
    count = 1
    for i in range(num):
        restr = ''
        chars = string.ascii_lowercase+ string.digits
        for i in range(len):
            restr += random.choice(chars)

        f.write( str(count)+ ' ' + restr +'\n')
        count += 1

    f.close()


if __name__ == '__main__':

    rand_str(200,20)


知识点:

1.随机取值:

 random.choice

2.w是写入,wb就是写入二进制文件了。

f = open('file.txt','w')

3.int转为str

str(count)


二、把1中生成的随机码存到数据库中

#-*- coding:utf-8 -*-

'''
02
'''

import string
import random
import pymysql


#用于生成随机字符串List的函数

def geneRandStr(num,len=7):

    strList = []

    for i in range(num):
        restr = ''
        chars = string.ascii_lowercase + string.digits
        for i in range(len):
            restr += random.choice(chars)
        strList.append(restr)
    return strList

#把字符串List存入数据库
def storeInMysql(codeList):

    try:
        conn = pymysql.connect(host='127.0.0.1',user = 'root',
                           password = '123456',db = 'pytest')
        cur = conn.cursor()
    except BaseException as e:
        print(e)
    else:
        try:
            cur.execute('DROP DATABASE pytest ')
            cur.execute('CREATE DATABASE IF NOT EXISTS pytest ')
            cur.execute('USE pytest')
            cur.execute('''CREATE TABLE IF NOT EXISTS code(
              id INT NOT NULL AUTO_INCREMENT,
              code VARCHAR (32) NOT NULL,
              PRIMARY KEY (id)
              )''')

            for code in codeList:
                cur.execute('INSERT INTO code(code) VALUES (%s)',(code))
                cur.connection.commit()

        except BaseException as e:
            print(e)

    finally:
        cur.close()
        conn.close()


if __name__ == '__main__':
    storeInMysql(geneRandStr(20,10))








好的,以下是适合新手的20个Python练手小程序的代码实现: 1. 猜数字游戏 ```python import random number = random.randint(1, 100) guess = int(input("Guess a number between 1 and 100: ")) while guess != number: if guess < number: print("Too low!") else: print("Too high!") guess = int(input("Guess again: ")) print("You guessed it! The number was", number) ``` 2. 石头、剪子、布游戏 ```python import random options = ["rock", "paper", "scissors"] player = input("Choose rock, paper, or scissors: ") computer = random.choice(options) print("You chose", player) print("The computer chose", computer) if player == computer: print("It's a tie!") elif player == "rock" and computer == "scissors": print("You win!") elif player == "paper" and computer == "rock": print("You win!") elif player == "scissors" and computer == "paper": print("You win!") else: print("Computer wins!") ``` 3. 打印九九乘法表 ```python for i in range(1, 10): for j in range(1, 10): print(i, "*", j, "=", i*j) print() ``` 4. 计算器小程序 ```python num1 = float(input("Enter first number: ")) operator = input("Enter operator (+, -, *, /): ") num2 = float(input("Enter second number: ")) if operator == "+": print(num1 + num2) elif operator == "-": print(num1 - num2) elif operator == "*": print(num1 * num2) elif operator == "/": print(num1 / num2) else: print("Invalid operator") ``` 5. 猜单词游戏 ```python import random words = ["apple", "banana", "orange", "grape", "watermelon"] word = random.choice(words) print("Guess the word!") guess = input("Enter your guess: ") while guess != word: print("Wrong! Try again.") guess = input("Enter your guess: ") print("You guessed it! The word was", word) ``` 6. 简单的文本编辑器 ```python filename = input("Enter filename: ") try: with open(filename, "r") as file: contents = file.read() except FileNotFoundError: contents = "" new_contents = input("Enter new contents: ") with open(filename, "w") as file: file.write(new_contents) ``` 7. 文件拷贝小工具 ```python import shutil source = input("Enter source filename: ") destination = input("Enter destination filename: ") shutil.copy(source, destination) ``` 8. 网络爬虫小程序 ```python import requests from bs4 import BeautifulSoup url = input("Enter URL: ") response = requests.get(url) soup = BeautifulSoup(response.content, "html.parser") for link in soup.find_all("a"): print(link.get("href")) ``` 9. 简单的日历应用程序 ```python import calendar year = int(input("Enter year: ")) month = int(input("Enter month: ")) print(calendar.month(year, month)) ``` 10. 命令行版的日程管理器 ```python schedule = {} while True: command = input("Enter command (add, view, quit): ") if command == "quit": break elif command == "add": date = input("Enter date (YYYY-MM-DD): ") event = input("Enter event: ") schedule[date] = event elif command == "view": for date, event in schedule.items(): print(date, event) else: print("Invalid command") ``` 11. 电子邮件客户端 ```python import smtplib sender = input("Enter sender email: ") password = input("Enter sender password: ") recipient = input("Enter recipient email: ") subject = input("Enter email subject: ") body = input("Enter email body: ") message = f"Subject: {subject}\n\n{body}" server = smtplib.SMTP("smtp.gmail.com", 587) server.starttls() server.login(sender, password) server.sendmail(sender, recipient, message) server.quit() ``` 12. 音乐播放器 ```python import pygame pygame.init() file = input("Enter filename: ") pygame.mixer.music.load(file) pygame.mixer.music.play() while pygame.mixer.music.get_busy(): pygame.time.Clock().tick(10) ``` 13. 生成随机密码 ```python import random import string length = int(input("Enter password length: ")) characters = string.ascii_letters + string.digits + string.punctuation password = "".join(random.choice(characters) for i in range(length)) print(password) ``` 14. 生成随机验证码 ```python import random import string length = 6 characters = string.ascii_uppercase + string.digits code = "".join(random.choice(characters) for i in range(length)) print(code) ``` 15. 生成随机数序列 ```python import random length = int(input("Enter sequence length: ")) numbers = [random.randint(1, 100) for i in range(length)] print(numbers) ``` 16. 图片转换小工具 ```python from PIL import Image filename = input("Enter filename: ") image = Image.open(filename) new_filename = input("Enter new filename: ") image.save(new_filename) ``` 17. 图片压缩小工具 ```python from PIL import Image filename = input("Enter filename: ") image = Image.open(filename) quality = int(input("Enter quality (1-100): ")) new_filename = input("Enter new filename: ") image.save(new_filename, optimize=True, quality=quality) ``` 18. 生成条形码和二维码 ```python import barcode from barcode.writer import ImageWriter from qrcode import QRCode, constants from qrcode.exceptions import DataOverflow data = input("Enter data: ") barcode_type = input("Enter barcode type (EAN13, Code128): ") if barcode_type == "EAN13": barcode_class = barcode.get_barcode_class("ean13") elif barcode_type == "Code128": barcode_class = barcode.get_barcode_class("code128") else: print("Invalid barcode type") barcode_image = barcode_class(data, writer=ImageWriter()) barcode_image.save("barcode") qr_code = QRCode(version=None, error_correction=constants.ERROR_CORRECT_L, box_size=10, border=4) try: qr_code.add_data(data) qr_code.make(fit=True) qr_code_image = qr_code.make_image(fill_color="black", back_color="white") qr_code_image.save("qr_code") except DataOverflow: print("Data too long for QR code") ``` 19. 短信发送小工具 ```python import requests url = "https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages.json" account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" auth_token = "your_auth_token" from_number = input("Enter from number: ") to_number = input("Enter to number: ") message_body = input("Enter message body: ") payload = {"To": to_number, "From": from_number, "Body": message_body} response = requests.post(url, auth=(account_sid, auth_token), data=payload) print(response.text) ``` 20. 网络图片下载工具 ```python import requests url = input("Enter URL: ") filename = input("Enter filename: ") response = requests.get(url) with open(filename, "wb") as file: file.write(response.content) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值