如何使这个IF语句工作

时间:2014-11-25 03:20:35

标签: python

fgrades=["90","70","63","81","49"]   
a=0
b=0    
c=0    
d=0    
f=0    
grades=raw_input("enter your final grade: ")    
fgrade+=(grades,)

for i in range(len(fgrades)):
   if fgrades[i]>="90":
      a+=1        
   elif fgrades[i]>="80":
      b+=1        
   elif fgrades[i]>="70":
       c+=1        
   elif fgrades[i]>="60":
       d+=1        
   else:
       f+=1

print a,"\n",b,"\n",c,"\n",d,"\n",f

在我将所有数字放入所有数字之后转入F.即使你输入96输入也会发生这种情况。

3 个答案:

答案 0 :(得分:2)

我在这里看到的一个问题是你试图对字符串而不是数字执行不等式。尝试将输入值转换为整数。

如果将值存储为整数的fgrades,例如[90,70,60,88,96],那么这应该有效:

fgrades=[90, 70, 60, 88, 96]

a=0

b=0

c=0

d=0

f=0

grades=raw_input("enter your final grade: ")

# Clean up grades, and convert to an integer
grades = int(grades.strip().replace(" ","")

fgrades.append(grades)

for i in range(len(fgrades)):

   if fgrades[i]>=90:
      a+=1        
   elif fgrades[i]>=80:
      b+=1        
   elif fgrades[i]>=70:
       c+=1        
   elif fgrades[i]>=60:
       d+=1        
   else:
       f+=1

print a,"\n",b,"\n",c,"\n",d,"\n",f

否则,如果您出于某种原因要求将成绩存储为字符串,例如[“90”,“70”,“63”,“81”,“49”],那么以下内容对您有用:

fgrades= ["90","70","63","81","49"] 

a=0

b=0

c=0

d=0

f=0

grades=raw_input("enter your final grade: ")

# Clean up grades
grades = grades.strip().replace(" ","")

fgrades.append(grades)

for i in range(len(fgrades)):

   if int(fgrades[i])>=90:
      a+=1        
   elif int(fgrades[i])>=80:
      b+=1        
   elif int(fgrades[i])>=70:
       c+=1        
   elif int(fgrades[i])>=60:
       d+=1        
   else:
       f+=1

print a,"\n",b,"\n",c,"\n",d,"\n",f

答案 1 :(得分:1)

这里有一些建议,您可以考虑使用您的代码。

首先,您可以从

更改for循环语句
for i in range(len(fgrades)):
    ...

for i in fgrades:
    ....

所以随后,您只需要对值i进行比较,而不是fgrades[i]

所以你的代码将是

fgrades=[]
a=0
b=0
c=0
d=0
f=0

grades=raw_input("enter your final grade: ")

# Clean up grades, and convert to an integer
grades = int(grades.strip().replace(" ","")

fgrade.append(grades)

for i in fgrade:

   if i>=90:
      a+=1        
   elif i >=80:
      b+=1        
   elif i >=70:
       c+=1        
   elif i >=60:
       d+=1        
   else:
       f+=1

print a,"\n",b,"\n",c,"\n",d,"\n",f

答案 2 :(得分:0)

首先,您尝试对字符串进行大于或等于操作的数值。如果要比较数字,必须将它们转换为数字数据类型(int,float,decimal)。

其次,安迪的评论也是正确的。 fgrade尚未作为变量/对象存在。

fgrades=[]   
a=0
b=0    
c=0    
d=0    
f=0    
grades=int(raw_input("enter your final grade: "))
fgrades += (grades,)

for i in range(len(fgrades)):
   if fgrades[i]>=90:
      a+=1        
   elif fgrades[i]>=80:
      b+=1        
   elif fgrades[i]>=70:
       c+=1        
   elif fgrades[i]>=60:
       d+=1        
   else:
       f+=1

print a,"\n",b,"\n",c,"\n",d,"\n",f