Slides badge

Conditional loops

Explain what is wrong with each program

for x = 0 to 5:
  print(x)
for x = 5 to 3:
  print(x)

Explain what is wrong with each program

for x in range(0, 5):
  print(x)
for x in range(3, 5):
  print(x)

Learning Intentions

  • Understand what a loop is in computer science
  • Implement a conditional loop in Python

Success Criteria

  • I can explain the benefit of loops in computer programming
  • I am able to develop a conditional loop in Python

Conditional loops

  • There are two kinds of loops: fixed loops and conditional loops
  • We've already looked at fixed loops and we've also already looked at conditions.

A conditional loop

  • A condition will always evaluate to True or False.
  • Conditional loops use a condition to loop whilst a condition evaluates to true.
  • Some conditional loops never evaluate to True and therefore are considered to be infinite loops.
  • Python has several types of conditional loops, but the one we are interested in is the while loop.

For each of the following, state whether it is true or false:

 

 

 

 

 

 

 

 

 

 

 

Task

x = True
y = False

print(x and y)
x = 54
y = 24

print(x > y)
x = 54
y = 24

print(x < y or y > 5)
x = True
y = True

print(not(x or y))

A while loop

  • While loops will continue to loop while a condition is True.
  • If the condition is initially false, then the loop will never run.
while True:
  print("This loop is never gonna end!")
n = 0
while n < 100:
  print(n)
  n = n + 1

A login system

print("Please insert your username")
username = input()
print("Please insert your password")
password = input()

if username == "Hamish" and password == "pass":
  print("Welcome!")
else:
  print("Login incorrect")

A login system - using loops

print("Please insert your username")
username = input()
print("Please insert your password")
password = input()
attempts = 0

while username != "Hamish" and password != "pass":
  print("Login incorrect")
  print("Please insert your username")
  username = input()
  print("Please insert your password")
  password = input()
  attempts = attempts + 1

print("Welcome", "It took you", attempts, "to login")

Conditional Loops

Complete the Conditional Loops worksheet

 

Complete the Python Conditional Loops (While) tasks in the Python book on page 31

Task

Presentation Overview
Close
JB
S3 Computer Science :: Software Development :: Conditional loops
© J Balfour
06:32 | 30-09-2023
Slideshow Outline
Save progress Show presenter mode Canvas controls Show widget screen
Dark Mode Bold Text Accessibility
Random Number Generator Timer Binary & decimal converter Show Python editor Show Knox 90
Provide feedback Help
!
Keywords
    Sections
      Binary conversion
      Denary to binary conversion
      Binary to denary conversion
      Slideshow Outline
      Feedback 👍
      Accessibility

      Apply a filter:

      ×
      All slide files