What is the output of the following program?

fortnight_players = 784
wow_players = 813

if fortnight_players > 700 and wow_players > 700:
  print("The competition can go ahead")
  if fortnight_players > wow_players:
    print("We have more Fortnight players")
  elif:
    print("We have more WoW players")

What is the output of the following program?

fortnight_players = 784
wow_players = 813

if fortnight_players > 700 and wow_players > 700:
  print("The competition can go ahead")
  if fortnight_players > wow_players:
    print("We have more Fortnight players")
  else:
    print("We have more WoW players")

The competition can go ahead
We have more WoW players

Fixed loops

Learning Intentions

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

Success Criteria

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

A loop?

In pairs, discuss for three minutes what you think a loop would do in a computer programming language.

Task

What a loop does

  • A loop will do something over and over until a termination case has been met. This basically means when the computer is told that it is time to stop.
  • Some loops, called infinite loops, will never terminate. An example of this is one that will keep a slideshow on a website running forever.
  • The body of the loop is the code that is repeated.
  • There are two kinds of loops: fixed loops and conditional loops

Advantages of loops

  • Write once, do many times. Just write the code to loop and the body once rather than copying and pasting over and over.
  • The number of times a loop is needed might need to change often (even whilst the program runs). If you did this manually you would need to copy and paste or delete code over and over (example in next slide)

Without loops

n = 0

print(n)
n = n + 1

print(n)
n = n + 1

print(n)
n = n + 1

print(n)
n = n + 1

With loops

n = 0

for i in range(0, 4):
  print(n)
  n = n + 1

With loops - simplified

for i in range(0, 4)
  print(i)

i is a local variable that changes each time the loop repeats

Fixed loops

  • A fixed loop will loop a set number of times.
  • We give a fixed loop a range to loop between a lower number (e.g. 0) and a larger number (4) that tells the computer how many times to loop. Range is a Python predefined function, so its arguments go between the brackets and are separated by a comma:
    • range(0, 4)
  • We can figure out how many times it will loop by taking the smaller number from the bigger number:
    • range(0, 4) : 4 – 0 = 4
    • range(10, 5) : 10 - 5 = 5

How many times do the following loop?

 

range(0, 5)
range(9, 12)
range(15, 30)

Task

How many times do the following loop?

 

range(0, 5) - 5 times
range(9, 12) - 3 times
range(15, 30) - 15 times

Task

Complete the Python for loops tasks.

Task

JB
6 Software Development : 5.1 Fixed loops
© J Balfour
Tools