简体   繁体   中英

How to nest if statement in a while loop in python 3

I am having trouble with the below code

try:
    while True:
        # Get next line from file
        line = fileHandler.readline()
        plaintext = pow(int(line), a, n)    # a, n and line read from file are integers.
        if len(str(plaintext)) % 2 != 0:
            plaintext = '0{}'.format(plaintext)  # adding zero if odd no of digits
            i = 0
            while i < len(plaintext) - 1:
                print(plaintext)
                row = int(plaintext[i])
                col = int(plaintext[i + 1])
                decrypted.append(matrix[row][col])
                if row > 0:
                    row -= 1
                print(matrix[row][col - 1])
                i = i + 2

        print(plaintext)
        if not line:
            print(decrypted)
            break
except ValueError:
    pass

When len(plaintext) % 2.= 0 fails the code in the while loop below it fails to execute. I know I have the while loop inside the if loop so it happens, But when I move the while loop out of if. nothing is executed. Can someone tell me what I am doing wrong.

I get the following output now:

19475276822512119441620228045431117884359382536936226816 05297161768145254779131968343762551184670149997720486635

H

05297161768145254779131968343762551184670149997720486635

p

05297161768145254779131968343762551184670149997720486635

&

The operations for the first line is not executed but they are performed when if

len(str(plaintext)) % 2 != 0:
            plaintext = '0{}'.format(plaintext)

this condition is true.

I hope I am clear. Thank you!

When len(plaintext) % 2 != 0 fails the code in the while loop below it fails to execute

Yes, that's how if statements work

when I move the while loop out of if, nothing is execute

It's not clear how far outside you moved it, but it still needs to be within the outer while loop, and you can use a range rather than another while loop

while True:
    ... 
    plaintext = str(pow(int(line), a, n)) 
    if len(plaintext) % 2 != 0:
        plaintext = '0{}'.format(plaintext)  # adding zero if odd no of digits
    # indent if you only want to execute this for odd length numbers 
    for i in range(0, len(plaintext), 2):
        print(plaintext)
        # ... 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM