[英]if statement not working within for loop
I am a beginner. 我是初学者。 I am doing an iterative calculation in python like
我正在像这样在python中进行迭代计算
for i in range(30):
if i<10:
p = 1
if 10<=i<20:
p = 2
else:
p = 3
however, when I run the code, for the if i<10 case, I am getting p=3 which is the else case. 但是,当我运行代码时,对于i <10的情况,我得到p = 3,这是其他情况。 I get correct p = 2 in second case.
在第二种情况下,我得到正确的p = 2。 What is wrong with this code?
此代码有什么问题?
For you code, the first if
and the else
statement will both run when i < 10
. 对于您的代码,当
i < 10
时,第一个if
和else
语句都将运行。 Maybe you should change your second if
to elif
: 也许你应该改变你的第二个
if
以elif
:
for i in range(30):
if i<10:
p = 1
elif 10<=i<20:
p = 2
else:
p = 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.