簡體   English   中英

PYTHON3 - 我可以在函數之外存儲在函數中創建的變量嗎

[英]PYTHON3 -Can I store variables created in a function outside of the function

import random, secrets

e = 7
M = 11

# Extended euclidean algorithm function
def extended_euclidean(a, b):
    r, r1, s, s1, t, t1 = b, a, 0, 1, 1, 0
    while r != 0:
        q = (r1 // r)
        (r1, r) = (r, r1 - q * r)
        (s1, s) = (s, s1 - q * s)
        (t1, t) = (t, t1 - q * t)
    d = r1
    x = s1
    y = t1

    if d == 1:
        return True, d, x, y
    else:
        return False

gcd, d, y = (extended_euclidean(e,M))
print("GCD= ", str(gcd), "d = ", str(d), "y= ", y)

如何從我的函數中獲取變量 d、x 和 y 以便在函數之外使用? 當我使用 gcd,d,y=(extended_euclidean(e,M)) ValueError: too many values to unpack (expected 3)" ))

由於不清楚應該返回什么,建議創建一個具有您想要的值作為屬性的對象。 像這樣的東西(雖然我不確定 gcd 和 d 是什么,這可能需要調整):

class ExtendedEuclidean:

    def __init__(self, a, b):
        r, r1, s, s1, t, t1 = b, a, 0, 1, 1, 0
        while r != 0:
            q = (r1 // r)
            (r1, r) = (r, r1 - q * r)
            (s1, s) = (s, s1 - q * s)
            (t1, t) = (t, t1 - q * t)
        if r1 == 1:
            self.ok = True
            self.gcd = r1
            self.x = s1
            self.y = t1
        else:
            self.ok = False
            self.gcd = None
            self.x = None
            self.y = None


ee = ExtendedEuclidean(7, 11)

if ee.ok:
    print("GCD= ", str(ee.gcd), "x = ", str(ee.x), "y= ", ee.y)
else:
    print("not ok")

暫無
暫無

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

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