🍄 Генератор фейковых данных на python
Исходный код:
Результат в ролике: https://vt.tiktok.com/ZS2gN7pqw/
Исходный код:
from faker import Faker
from time import sleep
faker = Faker('Ru')
def generate_dates():
while True:
name = faker.name()
email = faker.email()
address = faker.address()
phone_number = faker.phone_number()
city = faker.city_name()
sleep(1.5)
print(f'\n{name}')
print(email)
print(address)
print(phone_number)
print(city)
generate_dates()
Результат в ролике: https://vt.tiktok.com/ZS2gN7pqw/
👍5❤🔥1❤1
🔋 Узнаём заряд батареи пк с помощью python
Исходный код:
Результат в ролике: https://www.tiktok.com/t/ZTFDbEQQd/
Исходный код:
import tkinter as tk
import psutil
from tkinter import messagebox
def check():
bat = psutil.sensors_battery()
percent = f'Заряд: {int(bat.percent)}%'
return percent
def show_battery_status():
status = check()
messagebox.showinfo("Заряд батареи", status)
root = tk.Tk()
root.title("Статус Заряда Батареи")
root.geometry("300x150")
button = tk.Button(root, text="Показать заряд батареи", command=show_battery_status, font=('Arial', 16))
button.pack(pady=50)
root.mainloop()
Результат в ролике: https://www.tiktok.com/t/ZTFDbEQQd/
🔥3❤1👍1
🥑 Матрица как в фильмах на python
Исходный код:
Результат в ролике: https://vt.tiktok.com/ZS27LaH1j/
Исходный код:
import pygame
import random
pygame.init()
font = pygame.font.SysFont('宋体', 25)
screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
screenwidth = screen.get_width()
screenheight = screen.get_height()
surface = pygame.Surface((screenwidth, screenheight), pygame.SRCALPHA)
surface.fill((0, 0, 0, 10))
texts = [font.render(i, True, (0, 255, 0)) for i in ['0', '1']]
lst = list(range(99))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
if event.type == pygame.KEYUP:
if event.key == pygame.K_ESCAPE:
pygame.display.set_mode((600, 600))
if event.key == pygame.K_f:
pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
pygame.time.delay(50)
screen.blit(surface, (0, 0))
for i in range(len(lst)):
text = random.choice(texts)
screen.blit(text, (i * 20, lst[i] * 20))
lst[i] += 1
if random.random() < 0.05:
lst[i] = 0
pygame.display.flip()
Результат в ролике: https://vt.tiktok.com/ZS27LaH1j/
👍5
⚓ Танцующий человечек на python
Исходный код:
Результат: https://www.tiktok.com/t/ZTF5SHGtu/
Исходный код:
import time
import os
frames = [
r"""
O
/|\
/ \
""",
r"""
\O/
|
/ \
""",
r"""
O
/|\
/ \
""",
r"""
O/
|
/ \
"""
]
def clear_console():
os.system('cls' if os.name == 'nt' else 'clear')
while True:
for frame in frames:
clear_console()
print(frame)
time.sleep(0.3)
Результат: https://www.tiktok.com/t/ZTF5SHGtu/
😁5❤1👍1
🌀 Конвертер валют на python
Исходный код:
Результат в ролике: https://www.tiktok.com/t/ZTFudeKQa/
Исходный код:
import requests
available_currencies = {
"USD": "Доллар США",
"EUR": "Евро",
"RUB": "Российский рубль",
"KZT": "Казахский тенге",
"UAH": "Украинская гривна",
}
def display_available_currencies():
print("Доступные валюты:")
for code, name in available_currencies.items():
print(f"{code}: {name}")
def get_exchange_rate(base_currency, target_currency):
url = f"https://api.exchangerate-api.com/v4/latest/{base_currency}"
response = requests.get(url)
data = response.json()
rate = data["rates"].get(target_currency)
if rate:
return rate
else:
return None
def convert_currency(amount, base_currency, target_currency):
rate = get_exchange_rate(base_currency, target_currency)
if rate:
return amount * rate
else:
print(f"Невозможно конвертировать {base_currency} в {target_currency}")
display_available_currencies()
amount = float(input("Введите сумму: "))
base_currency = input("Из какой валюты? (например, USD): ").upper()
target_currency = input("В какую валюту конвертировать? (например, RUB): ").upper()
converted_amount = convert_currency(amount, base_currency, target_currency)
if converted_amount:
print(f"{amount} {base_currency} = {converted_amount:.2f} {target_currency}")
Результат в ролике: https://www.tiktok.com/t/ZTFudeKQa/
👍7
🔸 Прикольная игра на python
Исходный код:
Исходный код:
import curses
import random
import time
stdscr = curses.initscr()
curses.curs_set(0)
sh, sw = stdscr.getmaxyx()
w = curses.newwin(sh, sw, 0, 0)
w.keypad(1)
w.timeout(100)
cat_x = sw // 2
cat_y = sh - 1
fish_x = random.randint(1, sw - 1)
fish_y = 0
score = 0
while True:
w.clear()
w.border(0)
w.addstr(cat_y, cat_x, "😺")
w.addstr(fish_y, fish_x, "🐟")
w.addstr(0, 2, f"Score: {score}")
key = w.getch()
if key == curses.KEY_LEFT and cat_x > 1:
cat_x -= 1
elif key == curses.KEY_RIGHT and cat_x < sw - 2:
cat_x += 1
fish_y += 1
if fish_y == sh:
fish_y = 0
fish_x = random.randint(1, sw - 1)
if fish_y == cat_y and fish_x == cat_x:
score += 1
fish_y = 0
fish_x = random.randint(1, sw - 1)
w.refresh()
time.sleep(0.1)
curses.endwin()
👍4❤1 1
💧Прикольный чат бот на python
Исходный код:
Ролик: https://www.tiktok.com/t/ZTFX1d5K7/
Исходный код:
import nltk
from nltk.chat.util import Chat, reflections
import random
pairs = [
[
r"Привет|Здравствуй|Добрый день",
["Привет! Как тебя зовут?",
"Здравствуйте! Как вас зовут?"]
],
[
r"Меня зовут (.*)",
["Приятно познакомиться, %1! Как я могу помочь вам сегодня?",
"Здравствуйте, %1! Как проходит ваш день?"]
],
[
r"(.*) как дела?",
["У меня всё отлично, спасибо! А у вас?",
"Отлично, как и всегда! А как у вас?"]
],
[
r"(.*) помощь(.*)",
["Конечно! В чем именно вам нужна помощь?",
"Я здесь, чтобы помочь вам. Какой вопрос у вас?"]
],
[
r"(.*) факт(.*)",
["Знаете ли вы, что дождевые черви имеют пять сердец?",
"Вот интересный факт: звезды могут быть на расстоянии до 13 миллиардов световых лет от нас!"]
],
[
r"(.*) шутка(.*)",
["Почему программисты не любят природу? Потому что в ней слишком много багов!",
"Какой лучший способ описать программиста? Они делают как будто знают, что делают!"]
],
[
r"(.*) игра(.*)",
["Давайте сыграем в 'Угадай число'! Задумайте число от 1 до 10. Я буду пытаться угадать его. Готовы? (да/нет)"]
],
[
r"да",
["Отлично! Ваше число? (помните, от 1 до 10)"]
],
[
r"(.*)",
["Извините, я не понимаю. Можете переформулировать?",
"Пожалуйста, уточните ваш вопрос. Я здесь, чтобы помочь!"]
]
]
chatbot = Chat(pairs, reflections)
def chat():
print("Добро пожаловать в чат! Пишите 'Выход', чтобы завершить.")
user_name = ""
while True:
user_input = input("Вы: ")
if user_input.lower() == 'выход':
print("Чат завершен.")
break
bot_response = chatbot.respond(user_input)
print(f"Бот: {bot_response}")
chat()
Ролик: https://www.tiktok.com/t/ZTFX1d5K7/
🔥8👍2🤪1
🌪 Распознавание лица на python
Исходный код:
Результат в ролике: https://www.tiktok.com/t/ZTFpogNRN/
Исходный код:
import cv2
import matplotlib.pyplot as plt
def face_recognition():
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
video_capture = cv2.VideoCapture(0)
while True:
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.1, 4)
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)
plt.imshow(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
plt.axis('off')
plt.show(block=False)
plt.pause(0.001)
plt.clf()
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()
face_recognition()
Результат в ролике: https://www.tiktok.com/t/ZTFpogNRN/
👍6
❄ Снегопад на python
Исходный код:
Результат в ролике: https://vt.tiktok.com/ZSjMpHrck/
Исходный код:
import pygame
import random
pygame.init()
WIDTH, HEIGHT = 800, 600
WHITE = (255, 255, 255)
BLUE = (0, 0, 128)
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Снегопад")
class Snowflake:
def init(self):
self.x = random.randint(0, WIDTH)
self.y = random.randint(-HEIGHT, 0)
self.size = random.randint(2, 6)
self.speed = random.uniform(1, 3)
self.wind = random.uniform(-0.5, 0.5)
def fall(self):
self.y += self.speed
self.x += self.wind
if self.y > HEIGHT:
self.y = random.randint(-50, -10)
self.x = random.randint(0, WIDTH)
if self.x < 0:
self.x = 0
elif self.x > WIDTH:
self.x = WIDTH
def draw(self):
pygame.draw.circle(screen, WHITE, (int(self.x), int(self.y)), self.size)
snowflakes = [Snowflake() for _ in range(200)]
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill(BLUE)
for snowflake in snowflakes:
snowflake.fall()
snowflake.draw()
pygame.display.flip()
pygame.time.delay(10)
pygame.quit()
Результат в ролике: https://vt.tiktok.com/ZSjMpHrck/
❤🔥4👍1🔥1
🔺️Тест на IQ с помощью python
Исходный код:
Результат: https://www.tiktok.com/t/ZTFc3kWgW/
Исходный код:
import tkinter as tk
from tkinter import messagebox
questions = [
{
"question": "Какое число должно быть следующим в ряду: 2, 4, 8, 16?",
"options": ["32", "24", "20", "18"],
"answer": "32"
},
{
"question": "Найдите лишнее слово: Кошка, Собака, Ягода, Курица",
"options": ["Кошка", "Собака", "Ягода", "Курица"],
"answer": "Ягода"
},
{
"question": "Продолжите последовательность: 1, 1, 2, 3, 5, 8, ?",
"options": ["10", "12", "13", "21"],
"answer": "13"
},
{
"question": "Сколько букв в русском алфавите?",
"options": ["30", "31", "32", "33"],
"answer": "33"
},
{
"question": "Как называется фигура с 8 сторонами?",
"options": ["Гексагон", "Гептагон", "Октагон", "Декагон"],
"answer": "Октагон"
}
]
class IQTestApp:
def init(self, root):
self.root = root
self.root.title("IQ Test")
self.score = 0
self.current_question = 0
self.setup_ui()
def setup_ui(self):
self.question_label = tk.Label(self.root, text="", wraplength=400, font=("Arial", 14))
self.question_label.pack(pady=20)
self.option_buttons = []
for i in range(4):
btn = tk.Button(self.root, text="", width=30, command=lambda idx=i: self.check_answer(idx))
btn.pack(pady=5)
self.option_buttons.append(btn)
self.next_button = tk.Button(self.root, text="Следующий вопрос", command=self.next_question)
self.next_button.pack(pady=20)
self.display_question()
def display_question(self):
q = questions[self.current_question]
self.question_label.config(text=q["question"])
for i, option in enumerate(q["options"]):
self.option_buttons[i].config(text=option)
def check_answer(self, selected_idx):
selected_option = questions[self.current_question]["options"][selected_idx]
if selected_option == questions[self.current_question]["answer"]:
self.score += 1
self.next_question()
def next_question(self):
self.current_question += 1
if self.current_question < len(questions):
self.display_question()
else:
iq_score = 80 + self.score * 10
messagebox.showinfo("Результат", f"Вы ответили правильно на {self.score} из {len(questions)} вопросов.\nВаш IQ: {iq_score}")
self.root.quit()
root = tk.Tk()
app = IQTestApp(root)
root.mainloop()
Результат: https://www.tiktok.com/t/ZTFc3kWgW/
👍5❤2🔥2
〽️ Анимированный текст с помощью python
Исходный код:
Пример анимации в ролике: https://vt.tiktok.com/ZSjA7c9TW/
Исходный код:
import pygame
import time
WIDTH, HEIGHT = 800, 200
text = 'Любой текст'
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
font = pygame.font.Font(None, 50)
clock = pygame.time.Clock()
displayed_text = ''
i = 0
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if i < len(text):
displayed_text += text[i]
i += 1
screen.fill((0, 0, 0))
rendered_text = font.render(displayed_text, True, (255, 255, 255))
screen.blit(rendered_text, (50, HEIGHT // 2))
pygame.display.flip()
time.sleep(0.1)
clock.tick(30)
pygame.quit()
Пример анимации в ролике: https://vt.tiktok.com/ZSjA7c9TW/
❤🔥4👍1 1