Numpy数组整数浮点数处理异常:Python脚本优化求助
Fixing Grade Validation Script Type Conversion Issues
Got it, let's tackle those frustrating type conversion problems in your grade checker script. The core issues are inconsistent handling of float inputs and unwanted integer truncation—here's a refined solution that enforces valid integer grades from your SevenGradeScale every time.
Original Problem Recap
Your current script has two key pain points:
- When the original element is a float, user input stays as a float unless it’s exactly an integer from the reference scale
- When the original element is an integer, float inputs get truncated (e.g., 7.5 becomes 7) instead of being rejected as invalid
Optimized Code
import numpy as np grades = np.array([-3, -10.5, 0, 7, 4, 8, 4, 7, 10, 5]) SevenGradeScale = np.array([-3, 0, 2, 4, 7, 10, 12]) SevenGradeScale = SevenGradeScale.astype(int) # Convert valid grades to a list for faster membership checks valid_grades = SevenGradeScale.tolist() for i in range(np.size(grades)): current_grade = grades[i] if current_grade not in valid_grades: while True: # Show targeted error message based on the current invalid value if isinstance(current_grade, float): print(f"\n{current_grade:.1f} is not a valid grade. You must enter an integer from the seven-grade scale: {valid_grades}") elif isinstance(current_grade, (int, np.integer)): print(f"\n{current_grade:d} is not within the seven-grade scale. Valid options: {valid_grades}") elif isinstance(current_grade, str): print(f"\n'{current_grade}' is not a valid grade. You must enter an integer from: {valid_grades}") # Handle input validation strictly try: user_input = input("Insert new grade: ").strip() # Reject floating-point inputs entirely by forcing integer conversion first new_grade = int(user_input) if new_grade in valid_grades: grades[i] = new_grade print(f"The grade has been changed to {new_grade:d}.") break else: print(f"{new_grade} isn't in the valid scale. Try again.") except ValueError: print("Invalid input! Please enter a whole integer from the valid scale list.") # Convert the entire array to integer type now all values are valid grades = grades.astype(int) print("\nFinal valid grades array:", grades)
Key Improvements
- Strict Integer Enforcement: We force users to input valid integers from the scale—no more floating-point inputs being silently converted or truncated. If someone enters
7.5, it’s rejected outright instead of becoming7. - Clearer Error Guidance: Users see exactly which values are allowed, reducing confusion about what counts as a valid input.
- Consistent Flow: Regardless of the original element’s type (float/int/str), the validation logic works the same way—check for integer input first, then verify it’s in the reference scale.
- Avoid Numpy Auto-Conversion: By validating inputs before assigning them to the array, we prevent numpy from silently altering values (like truncating floats to integers without user confirmation).
Example Run Output
-10.5 is not a valid grade. You must enter an integer from the seven-grade scale: [-3, 0, 2, 4, 7, 10, 12] Insert new grade: 10.7 Invalid input! Please enter a whole integer from the valid scale list. Insert new grade: 10 The grade has been changed to 10. 8 is not within the seven-grade scale. Valid options: [-3, 0, 2, 4, 7, 10, 12] Insert new grade: 7.5 Invalid input! Please enter a whole integer from the valid scale list. Insert new grade: 7 The grade has been changed to 7. 5 is not within the seven-grade scale. Valid options: [-3, 0, 2, 4, 7, 10, 12] Insert new grade: string Invalid input! Please enter a whole integer from the valid scale list. Insert new grade: 0 The grade has been changed to 0. Final valid grades array: [-3 10 0 7 4 7 4 7 10 0]
内容的提问来源于stack exchange,提问作者Edin Mahmutovic
相关产品推荐
相关产品推荐

