Print a Message
Part of the Python in a Game Window section of Coddy's Pygame journey. Lesson 2 of 32.
print() writes a line of text in the Console, the panel beside the game. Nothing appears in the window: print is for you, the programmer, to see what your program is doing.
print("Hello")
print(640 * 480)Text in quotes is printed as it is written. Leave the quotes out and Python works the value out first: print(640 * 480) shows 307200, while print("640 * 480") shows 640 * 480. In Python * means times.
Where a line goes matters. Every program in this section has the same three marked parts:
# Set things up here, before the game loop.
# Change things here, once a frame.
# Draw here, after the fill.The setup part runs once, at the start. The other two are inside the game loop, the lines under while running:, which run 60 times a second. So a print in the setup part shows once, and a print inside the loop floods the Console. Section 2 explains the loop line by line.
Challenge
EasyPrint two lines in the Console:
- In the setup part, before the game loop, replace
print("Hello")with a print ofThe night begins. - Below it, print the number of pixels in the window,
640 * 480, worked out by Python. - Keep both prints out of the game loop, so each runs once.
Try it yourself
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Night Sky")
clock = pygame.time.Clock()
# Set things up here, before the game loop.
print("Hello")
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Change things here, once a frame.
screen.fill((20, 24, 48))
# Draw here, after the fill.
pygame.display.flip()
clock.tick(60)
pygame.quit()
All lessons in Python in a Game Window
Practice on your own: Pygame playground