I am new to programming. I use Python 3.9.5 and VSCode on Windows 10. In video 14 titled "Exercise", chapter 3 titled "Control Flow" of Mosh Hamedani's "Complete Python Mastery" course, this assignment was provided:
Write a program that displays the even numbers between 1 to 10.
The output is supposed to be:
2
4
6
8
We have 4 even numbers
My program produced the intended output, but I was wondering how I can improve my code. I saw other people's answers to this question, but I'm focusing on how I can work on what I already have specifically.
number_of_numbers = 0
number = 0
while number < 8:
number += 2
number_of_numbers += 1
print(number)
print(f"We have {number_of_numbers} even numbers")
Some people suggested changes such as using range and for loops. However, when I implemented them, there came several issues.
for number in range(0, 10, 2): # The problem with this is that it prints 0 as well. How do I stop it from printing zero?
print(number)
number_of_numbers += 1
print(f"We have {number_of_numbers} even numbers") # This also says we have 9 even numbers instead of 4.
I was wondering if anyone could help improve my code and explain how to resolve those issues. Thank you very much in advance!
range(2,10,2)gives you a range starting from 2 instead. And no need to count as you go - if you havenumbers = range(2,10,2), thenlen(numbers)returns the 4 that you expect. \$\endgroup\$