in Python create a code that loop from 1 to 100 and print if the number is div by 2
- User
in Python create a code that loop from 1 to 100 and print if the number is div by 2
Assistant
Even Number Printer
Below is a Python code snippet that loops through numbers 1 to 100 and prints the numbers that are divisible by 2.
def print_even_numbers(): """ Prints numbers from 1 to 100 that are divisible by 2. """ for i in range(1, 101): if i % 2 == 0: print(i) # Example usage if __name__ == "__main__": print_even_numbers()How it works:
- The
range(1, 101)function generates numbers from 1 to 100. - The
forloop iterates over each number in the range. - The
ifstatement checks if the current numberiis divisible by 2 using the modulo operator%. If the remainder is 0, the number is even. - If the number is even, it is printed to the console.
Tips:
- The
rangefunction is exclusive of the end value, so we use101to include100in the range. - The modulo operator
%returns the remainder of the division, which is 0 for even numbers. - You can modify the code to print numbers divisible by other numbers by changing the divisor in the
ifstatement.
- The
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.