0% found this document useful (0 votes)
43 views14 pages

Understanding Loops in Programming

The document explains loops in programming, detailing their purpose as control structures for executing code repeatedly. It covers types of loops, including for loops and while loops, their usefulness, and introduces concepts like nested loops and loop control statements. Additionally, it provides practical code examples demonstrating the application of these loops in game development scenarios.

Uploaded by

benpeers777
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views14 pages

Understanding Loops in Programming

The document explains loops in programming, detailing their purpose as control structures for executing code repeatedly. It covers types of loops, including for loops and while loops, their usefulness, and introduces concepts like nested loops and loop control statements. Additionally, it provides practical code examples demonstrating the application of these loops in game development scenarios.

Uploaded by

benpeers777
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Loops

What are loops?


In programming, loops are control structures that allow you to repeatedly execute
a block of code. They are used when you need to perform a specific task or set of
tasks multiple times. If you ever find yourself copy and pasting code multiple
times, you should probably be using loops.
Types of loops: For loops
The for loop iterates over a sequence of elements, this includes a list, a tuple, a
dictionary, a set, a string, or a range. It executes a block of code for each item in the
sequence. The item part of the code can be used to differentiate the different
iterations of a for loop for example if you wanted to create bricks of 3 different
colours you could make an if statement inside the for loop that will change the colour
of the bricks after the item reaches a certain value. Here's the basic syntax of a for
loop:

for item in sequence:


# Code block to be executed
Why are for loops useful?
For loops are extremely useful for when you need to run code a SET number of
times. It saves time copy pasting the code over and over again and lets you do it
all in 1 block of code. For example if you wanted to create 30 aliens for a space
invaders game, you could use a for loop to generate all 30 aliens instead of having
to copy paste the code 30 times.
Types of loops: While loops
While Loop: The while loop repeatedly executes a block of code as long as a
given condition is true. The while-loop uses a boolean test expression to control
the run of the body lines. This condition uses logical operators such as == or <=.
Here's the basic syntax of a while loop:

while condition:
# Code block to be executed
Logical Operators
These are all the logical operators that you can use in while loops

1. Comparison Operators:
● Equal to: ==
● Not equal to: !=
● Greater than: >
● Less than: <
● Greater than or equal to: >=
● Less than or equal to: <=
2. Logical Operators:
● Logical AND: and
● Logical OR: or
● Logical NOT: not
Sentinel values
Sentinel values are special values that terminate a loop when they reached. For
example you could have a sentinel value in a game that ends the main game loop
and proceeds to a game over screen when the player reaches a certain amount of
points or lives.
Why are while loops useful
While loops are useful for when you want to iterate code an unknown amount of
times. Unlike for loops which saves you time spent copy and pasting, while loops
have functions that simply can’t be accomplished via other means such as running
code every frame in a game or continuing a program until the user decides to
close it themselves. For example if you made a program that calculated someones
grocery store order with tax included and you wanted to be able to enter in a new
order without closing the program you could use a while loop that would only close
when the player says “no” when they are asked if they want to start a new order.
Nested loops
Nested Loops: Python also allows you to have loops within loops, known as nested
loops. You can use nested loops to perform repetitive tasks within repetitive tasks.
Nested loops are useful because they allow you to repeat instructions within other
repeated instructions, enabling you to handle complex data structures, perform
repetitive tasks at different levels, and achieve more granular control over your
program's flow. Here's an example of a nested loop:

for i in range(1, 4):


for j in range(1, 4):
print(i, j)
Loop control statements
Loop control statements are used to change the flow of execution. These can be
used if you wish to skip an iteration or stop the execution.

The three types of loop control statements in python are the break statement
which stops the execution and brings the control out of the loop, the continue
statement which is used to skip the current iteration when the condition is met and
allows the loop to continue with the next iteration, and the pass statement which is
used when we want to do nothing when the condition is met.
Examples in my code #1: Main game loop
This is the loop that will run all of the code that I
need to repeat every frame such as the movement
code, drawing on the screen and moving the
computer controlled hitman.
Examples in my code #2: using a for loop to divide a sprite sheet into a list

for i in range(num_frames):
# Calculate the position and dimensions of the current frame
x = i * frame_width
y=0
rect = [Link](x, y, frame_width, frame_height)

# Extract the current frame from the sprite sheet


frame = [Link]([Link], [Link])
[Link](sprite_sheet, (0, 0), rect)

# Add the frame to the list


[Link](frame)

This for loop is apart of my divide sprite sheet function and it divides the
sprite sheet into 3 frames of animation for the player characters walk cycle.
Examples in my code #3: Game over screen
while not gameOn:

for event in [Link]():

if [Link] == [Link]:

[Link]()

[Link]()

[Link]((255, 255, 255))

[Link](gameOverText, (sw / 2 - gameOverText.get_width() / 2, 150))

[Link](finalScoreText,

(sw / 2 - finalScoreText.get_width() / 2, sh / 2 - finalScoreText.get_height() / 2))

[Link]()

This code uses the while loop to create a game over screen loop that begins when gameOn = False. Which happens after you run
out of lives, the loop displays a screen that says “Game Over” and displays your final score.
Examples in my code #4: Nested loop

This part of the code is a nested loop that checks for events such as the x in the
top right of the pygame window being pressed, which will close the game in this
code.

You might also like