RUVIDEO
Поделитесь видео 🙏

ChatGPT built a workable Calculator - Python

📁 Лайфхаки 👁️ 16 📅 02.12.2023

This video is about ChatGPT built a workable Calculator - Python

Remark: &lt replace the "less than" sign

===== Python Code =====
import pygame
import sys

# Initialize Pygame
pygame.init()

# Set the screen size
size = width, height = 300, 400
screen = pygame.display.set_mode(size)

# Set the colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY = (128, 128, 128)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

# Set the font
font = pygame.font.Font(None, 32)

# Set the calculator variables
num1 = ''
num2 = ''
operator = ''
result = ''

# Create the display text surface
display_text = font.render(result, True, BLACK)
display_rect = display_text.get_rect(center=(150, 50))

# Create the button surfaces
button_size = (60, 60)
button_spacing = 10
button_x = (width - button_size[0] * 4 - button_spacing * 3) / 2
button_y = 120
button_rects = []
for row in range(4):
for col in range(4):
button_rects.append(pygame.Rect(button_x + (button_size[0] + button_spacing) * col,
button_y + (button_size[1] + button_spacing) * row,
*button_size))

# Set the button labels
button_labels = ['7', '8', '9', '/',
'4', '5', '6', '*',
'1', '2', '3', '-',
'C', '0', '=', '+']

# Create the button text surfaces
button_text_surfaces = []
for label in button_labels:
text_surface = font.render(label, True, BLACK)
button_text_surfaces.append(text_surface)

# Start the game loop
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
# Check if a button was clicked
for i, rect in enumerate(button_rects):
if rect.collidepoint(event.pos):
# Handle button click
button_label = button_labels[I]
if button_label.isdigit():
if operator:
if len(num2) &lt 8: # Only allow 8 digits for num2
num2 += button_label
else:
if len(num1) &lt 8: # Only allow 8 digits for num1
num1 += button_label
result = num1 + operator + num2
elif button_label in ['+', '-', '*', '/']:
if num1:
operator = button_label
result = num1 + operator
elif button_label == 'C':
num1 = ''
num2 = ''
operator = ''
result = ''
elif button_label == '=':
if num1 and num2 and operator:
num1 = str(eval(num1 + operator + num2))
num2 = ''
operator = ''
result = num1
display_text = font.render(result[-8:], True, BLACK) # Only display the last 8 characters
break

# Clear the screen
screen.fill(WHITE)

# Draw the display
pygame.draw.rect(screen, GRAY, (50, 20, 200, 60))
screen.blit(display_text, display_rect)

# Draw the buttons
for i, rect in enumerate(button_rects):
pygame.draw.rect(screen, BLUE, rect)
screen.blit(button_text_surfaces[i], rect.inflate(-20, -20))

# Draw the number display rectangle
pygame.draw.rect(screen, BLACK, (50, 20, 200, 60), 2)

# Update the screen
pygame.display.flip()

=====================

Background music: Almonds and Olives - Aaron Lieberman.mp3 (from Youtube audio library)

=====================

#chatgpt
#pythonprogramming
#clock
#calculator

Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «ChatGPT built a workable Calculator - Python», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.

Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.

Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!

Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.