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 循环完全执行后执行一次。

为了在 print 循环的每次迭代中执行 for 语句,您需要在 for 循环的范围内缩进它。

关于python - if 条件内的 for 循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30152428/

10-12 18:33