Python For和If函数
我想计算所有不同L值的x,然后打印结果。 我做错了什么Python For和If函数,python,Python,我想计算所有不同L值的x,然后打印结果。 我做错了什么 P=3 I=2 L = [2,4,6,8,10] x = (P * L * y)/ I for i in L(): if x <= 305: print "this" + L() + "will not work" else: print "this" + L() + "will not work" P=3 I=2 L=[2,4,6,8,10] x=(P*L*y)/I 因为我在L(
P=3
I=2
L = [2,4,6,8,10]
x = (P * L * y)/ I
for i in L():
if x <= 305:
print "this" + L() + "will not work"
else:
print "this" + L() + "will not work"
P=3
I=2
L=[2,4,6,8,10]
x=(P*L*y)/I
因为我在L()
如果x你没有指定取L
的哪个值,也没有在x
的等式中指定y
的值,我想你想要的是:
while i < len(L):
x = (P * L[i] * y)/ I
if x <= 305:
print "this" + L[i] + "will work"
else:
print "this" + L[i] + "will not work"
而i 如果x我猜,但这修复了您的语法和语义错误:
- 您没有定义y
- 您对列表L的访问在多个地方不正确
- 您的计算超出了循环,因此x永远不会
改变
- 您在if的两个分支中打印了相同的内容
代码:
根据您的要求,您应该遍历L中的所有值
试试这个代码
P=3
I=2
L = [2,4,6,8,10]
x=[]
y=?
for i in L:
x.append((P * i * y)/I)
for idx,i in enumerate(x):
if x <= 305:
print "this" + L[idx] + "will not work"
else:
print "this" + L[idx] + "will not work"
P=3
I=2
L=[2,4,6,8,10]
x=[]
y=?
对于L中的i:
x、 附加((P*i*y)/i)
对于idx,枚举(x)中的i:
如果x尝试将x=(P*L*y)/I
移动到for
循环中。使用i
而不是L
L()
也不正确。L
是一个列表,而不是一个函数。首先,你需要查阅你的课堂资料,了解基本的语言语法。您需要学习正确表达列表引用。您发布的代码正在尝试调用函数L。这不会执行:i逐步遍历L的元素;这不是一个合适的索引,你是对的。我编辑了我的答案以使用while循环。OP还需要为y声明一个值。请在发布之前运行您的代码。这一点我早就知道了。
this 2 is small enough
this 4 is small enough
this 6 is small enough
this 8 is small enough
this 10 is small enough
P=3
I=2
L = [2,4,6,8,10]
x=[]
y=?
for i in L:
x.append((P * i * y)/I)
for idx,i in enumerate(x):
if x <= 305:
print "this" + L[idx] + "will not work"
else:
print "this" + L[idx] + "will not work"