Write a short program to print all the even numbers 1 to 100

To begin with, we will need to make a loop which iterates (loops) 10 times, which we can use the for statement for:for value in range (1,101): // do something - this is a comment Note, here we use the range function which returns all the numbers in the given range - inclusive of the first parameter and exclusive of the last parameter - hence why we give 101 as the second value so it executes when value = 100 but not value = 101. This loop will iterate from when value = 1 to when value = 100, with the value increasing by 1 each time. Therefore the next step is to test whether value is a multiple of 2 - which can be done with the modulus operator (%). This returns the remainder eg. 7 % 2 = 1, so if in our case value is even then the remainder will be 0 (as every even number is a multiple of 2). We can implement this within the for loop, as we want this to condition to be checked for every value:for value in range (1,101): if value % 2 == 0: // do something In this case, we will only access the commented line '// do something' when value is even (or a multiple of 2).Finally, we want to print out value, but only when it is even. This is simply done with a print statement inside our new if statement, meaning value will be printed to the terminal - but only when it is even.for value in range (1,101): if value % 2 == 0: print(value) There we have it - our loop should output all the even values from 1 to 100 to the terminal! However, this wasn't the most optimum solution! We could have included an extra parameter in the range function which defines the step (how much to increment value by in each iteration), and by setting this to 2 this would straight away mean value is increased by 2 every iteration. We could then simply print value - which would produce the same output as before! This method is preferred, as less iterations are done making the program faster to execute compared to our previous code.for value in range (1,101,2): print(value) Bingo! We now have 2 ways to do the same thing, one of which is an improved version of the other one! Our programs should output all the even numbers between 1 and 100 - exactly what we were asked to do in the question!

Answered by Sam P. Python tutor

1174 Views

See similar Python Mentoring tutors

Related Python Mentoring answers

All answers ▸

What's the difference between a local and a global variable?


How would you loop over every key and value in a python dictionary?


How would you write a while loop to print all even numbers from 1-10?


Manually implement a function that finds the smallest value in a list of integers and print it.


We're here to help

contact us iconContact usWhatsapp logoMessage us on Whatsapptelephone icon+44 (0) 203 773 6020
Facebook logoInstagram logoLinkedIn logo

© MyTutorWeb Ltd 2013–2024

Terms & Conditions|Privacy Policy