运行生成两输入值间偶数的代码时遭遇索引越界错误求助
Fixing Your IndexError & Even Number List Code
Hey Zachary, let's break down exactly what's causing that index list out of range error and get your code working properly to output even numbers between two values.
The Root Cause of the IndexError
That error pops up because of this line in your code:
if ((List[j] % 2) - (List[j]/2)) > l :
Here's why:
- Your
jvariable counts how many elements you add toList—by the end of theforloop,jequals the length ofList. - But list indexes start at 0, so the last element in
Listis at indexlen(List) - 1. Trying to accessList[j]means you're asking for an element that doesn't exist, hence the out-of-range error.
Other Issues in Your Code
Beyond the index error, there are a few other problems keeping your code from working as intended:
- Incorrect even number check: The expression
((List[j] % 2) - (List[j]/2)) > ldoesn't actually identify even numbers. A simplenum % 2 == 0is the right way to check if a number is even. - Syntax error in
remove:List.remove[j]uses square brackets, butremove()is a method—you need to use parentheses likeList.remove(item). - Local variable scope: The
Listinside yourTough1()function is local, so trying toprint Listoutside the function will throw another error. - Unnecessary loop complexity: You adjusted
v = v-1and then incrementediinside the loop, which makes your range logic harder to follow and could skip values accidentally.
Fixed Code (Python 2, for JGrasp)
Here's a cleaned-up version that does exactly what you want—collect and print even numbers between your input values:
def Tough1(): # Get user input for min and max values min_num = int(raw_input("Enter your smallest #: ")) max_num = int(raw_input("Enter your largest #: ")) even_numbers = [] # Iterate through every number from min to max (inclusive) for num in range(min_num, max_num + 1): # Check if the number is even if num % 2 == 0: even_numbers.append(num) # Print the result clearly print("Even numbers between {} and {}:".format(min_num, max_num)) print(even_numbers) # Call the function to run the program Tough1()
Key Changes Explained
- Simplified input handling: Moved input collection inside the function to avoid messy global variables.
- Clear range logic:
range(min_num, max_num + 1)ensures we include the largest number the user enters. - Correct even check: Uses the standard
num % 2 == 0to identify even numbers. - Proper variable scope: The list of even numbers is created and used within the function, then printed directly without scope issues.
- Readable output: Added a descriptive line so the user knows exactly what's being printed.
内容的提问来源于stack exchange,提问作者Zachary Boyette
相关产品推荐
相关产品推荐

