簡體   English   中英

如何在 python 3 的 while 循環中嵌套 if 語句

[英]How to nest if statement in a while loop in python 3

我在使用以下代碼時遇到問題

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

當 len(plaintext) % 2.= 0 失敗時,下面的 while 循環中的代碼無法執行。 我知道我在 if 循環中有 while 循環,所以它發生了,但是當我將 while 循環移出 if 時。 什么都不執行。 有人可以告訴我我做錯了什么。

我現在得到以下 output:

19475276822512119441620228045431117884359382536936226816 05297161768145254779131968343762551184670149997720486635

H

05297161768145254779131968343762551184670149997720486635

p

05297161768145254779131968343762551184670149997720486635

&

第一行的操作未執行,但在 if 時執行

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

這個條件是真的。

我希望我很清楚。 謝謝!

當 len(plaintext) % 2 != 0 失敗時,下面的 while 循環中的代碼無法執行

是的,這就是 if 語句的工作方式

當我將while循環移出if時,什么都沒有執行

目前尚不清楚您將它移動了多遠,但它仍然需要在外部 while 循環內,並且您可以使用范圍而不是另一個 while 循環

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)
        # ... 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM