print "Select the action you want to perform(A or B)"
print "(A) uppper case"
print "(B) count number of lines"
option = raw_input("Enter your option(A or B):")
if option.upper() == "A":
for line in x:
line = line.upper()
print line
elif option.upper() == "B":
for line in x:
line = line.upper()
count = count + 1
print "total lines:", count
else:
print "incorrect option"
exit()
当用户输入 A 时,它仅以大写形式打印一行(最后一行)而不是 250 行。
计数完美。
附言我没有提交用于输入要打开的文件名的代码的第一部分。
最佳答案
只需将打印语句缩进为:
if option.upper() == "A":
for line in x:
line = line.upper()
print line
在 Python 中缩进起着非常重要的作用,通过缩进打印语句(就像在给定的代码中一样),解释器会认为它在 for
循环之外并且只会被执行在 for
循环执行完成后一次。
为了在 for
循环的每次迭代中执行 print
语句,您需要在 for 循环的范围内缩进它。
关于python - for 循环里面的 if 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30152428/