from numpy import *
a=array([[100,90,80,70,60,50,45],[90,80,70,60,50,40,30]])
L=["S", "A","B","C","D","E","F"]
n=int(input("Enter Marks Scored by Students: "))
for i in range(len(L)):
if a[0][i]>n and a[1][i]<n:
b=L[i]
print("Grade",b)
# Import the numpy library and give it an alias 'np' for easier referencing.
import numpy as np
# Create a 2D numpy array where the first row represents the upper bounds of grades and the second row represents the lower bounds.
a = np.array([[100, 90, 80, 70, 60, 50, 45], [90, 80, 70, 60, 50, 40, 30]])
L = ["S", "A", "B", "C", "D", "E", "F"]
n = int(input("Enter Marks Scored by Students: "))
# Create a mask (Boolean array) where each element is True if the student's score falls within the corresponding grade boundary.
grade_mask = (a[1] <= n) & (n < a[0])
# Find the index (position) of the grade boundary that the student's score falls into.
index = np.where(grade_mask)[0]
# If there's a match (i.e., the student's score falls within one of the grade boundaries), assign the corresponding grade label. Otherwise, assign "Invalid Score".
if index.size > 0:
grade = L[index[0]]
else:
grade = "Invalid Score"
print("Grade:", grade)
1条答案
按热度按时间5lhxktic1#
您的原始代码:
我对此有一些评论:
这通常被认为是不好的做法,因为它将所有函数从numpy导入到您的命名空间中,这可能会导致问题并覆盖现有函数,特别是如果您开始在较大的项目中定义自己的函数。更好的做法是
这个条件是有缺陷的。例如,如果学生得分为90,则90既不小于90也不大于100,并且不会被分配等级。此外,最好的做法是在条件语句中预测边缘情况。例如,输入超出范围的分数20会导致NameError,因为未定义B。
我在下面提供了一个改进的片段,并评论了我的更改: