Python技术问询:如何将数值范围传入函数以筛选4的倍数?
Hey there! The issue with your code is pretty straightforward: your VariableOf4 method is designed to take a single number as input, but you're passing an entire range object to it. Python can't perform the % (modulo) operation on a range directly, which is why you're seeing an error.
Let's go through two easy fixes for this:
Option 1: Modify the Function to Handle Iterables
Update your class method to accept any iterable (like a range, list, or tuple) and loop through each element inside the function. This is the cleaner approach if you want to pass collections of numbers directly:
class Calculator(): def find_multiples_of_4(self, numbers): # Loop through each number in the input iterable for num in numbers: if num % 4 == 0: print(f"{num} is a multiple of 4") # Create an instance of the Calculator class c = Calculator() # Define your range of numbers numbers = range(0, 100) # Pass the range directly to the modified method c.find_multiples_of_4(numbers)
Note: I adjusted the names to follow Python's PEP8 style guidelines (class names in PascalCase, method names in snake_case) and fixed the wording "Variable Of 4" to the more accurate "multiple of 4".
Option 2: Loop Through the Range When Calling the Function
If you want to keep the method focused on single numbers, just iterate over the range outside the function and pass each number individually:
class Calculator(): def is_multiple_of_4(self, num): if num % 4 == 0: print(f"{num} is a multiple of 4") c = Calculator() numbers = range(0, 100) # Loop through each number in the range and call the method for num in numbers: c.is_multiple_of_4(num)
Why Your Original Code Failed
When you run c.VariableOf4(numbers), you're passing a range object (not a single integer) to the method. The line num % 4 == 0 tries to compute the modulo of a range and an integer, which Python doesn't support—hence the TypeError: unsupported operand type(s) for %: 'range' and 'int' error you're seeing.
内容的提问来源于stack exchange,提问作者Alex Fate

