Skip to main content
 首页 » 编程设计

python之基于 python 3.x 列表中项目的条件 if 语句

2025年05月04日15cyq1162

如果不使用我们还没有“学到”的任何东西,我很难让这个作业发挥作用......

我必须全局定义一个变量,例如:

x = [80, 70, 65, 60, 50, 40, 45, 40, 35, 7, 0] 

给定这个全局变量,我需要用条件语句调用它的值来给出特定的结果。根据我们在类里面讲过的内容,我能想到的就是

x = [80, 70, 65, 60, 50, 40, 45, 40, 35, 7, 0] 
 
if x >= 50: 
    print("Good") 
else: 
    print("Bad") 

这根本行不通......但我必须要做的是:

for x in [80, 70, 65, 60, 50, 40, 45, 40, 35, 7, 0]: 
    if x >= 50: 
        print("Good") 
    else: 
        print("Bad") 

这显然对于赋值来说是 Not Acceptable ,因为全局变量没有按应有的方式定义。另外,赋值处理海龟模块,海龟的特征会根据列表中的整数值发生变化。

所以现在我已经在这里给出了一个与作业更直接相关的示例的答案..

import turtle 
 
def drawBar(t, height): 
    t.begin_fill() 
    t.left(90) 
    t.forward(height) 
    t.write('  '+ str(height)) 
    t.right(90) 
    t.forward(40) 
    t.right(90) 
    t.forward(height) 
    t.left(90) 
    t.end_fill() 
    if height >= 50: 
        t.fillcolor("blue") 
    elif height < 50 and height >= 30: 
        t.fillcolor("yellow") 
    else: 
        t.fillcolor("red") 
 
xs = [80, 70, 65, 60, 50, 40, 45, 40, 70, 7, 0] 
 
maxheight = max(xs) 
numbars = len(xs) 
border = 10 
 
bob = turtle.Turtle() 
bob.color("blue") 
bob.pensize(3) 
 
wn = turtle.Screen() 
wn.bgcolor("lightgreen") 
wn.setworldcoordinates(0-border,0-border,40*numbars+border,maxheight+border) 
 
for a in xs: 
    drawBar(bob, a) 
 
wn.exitonclick() 

到目前为止,if 语句并不能准确反射(reflect)程序中每个栏的栏高度,它似乎给出了几乎随机的颜色,但颜色总是组合在一起(它们不应该)。我需要每个条形根据其高度采用特定颜色,例如高于 50 为蓝色,小于 50 但等于或大于 30 为黄色,其他均为红色。

请您参考如下方法:

for a in x: 
    if a >= 50: 
        print("Good") 
    else: 
        print("Bad") 

这是您要找的吗?

确保你的“a”变量实际上是一个整数:

>>> str(1)>=5 
True