Freddy
Freddy

Reputation: 2382

for loop inside if condition

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()

When user enters A it prints only one line(last line) in upper case instead of 250 lines.

count works perfectly.


P.S. I have not submitted the first part of code which is for input of file name to be opened.

Upvotes: 3

Views: 14638

Answers (2)

ZdaR
ZdaR

Reputation: 22964

just indent your print statement as:

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

        print line

In Python Indentation plays a very important role, by de indenting the print statement(as it was in the given code), the interpreter would consider it outside the for loop and it would be executed only once after the complete execution of for loop.

In order to execute the printstatement at each iteration of the for loop you need to indent it inside the scope of for loop.

Upvotes: 6

tennabey
tennabey

Reputation: 293

the print line line should be indented to be inside the for line in x loop

Upvotes: 1

Related Questions