如果条件,在内部循环

Fre*_*ddy 3 python for-loop python-2.7

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()
Run Code Online (Sandbox Code Playgroud)

当用户输入A时,它只打印大写的一行(最后一行)而不是250行.

计数完美.


PS我还没有提交用于输入要打开的文件名的代码的第一部分.

Zda*_*daR 6

只需将您的print语句缩进为:

if option.upper() == "A":
    for line in x:
        line = line.upper()

        print line
Run Code Online (Sandbox Code Playgroud)

在Python中,缩进起着非常重要的作用,通过缩进print语句(就像它在给定的代码中一样),解释器会将它视为for循环外部,并且它将在完成for循环执行后仅执行一次.

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