Python 3.如何在函数的外部范围内使用函数中的变量?

问题描述 投票:2回答:2

我对编程非常陌生。我一直致力于一个项目,要求用户输入一个数字,这个数字通过一个数学系列。然后将输出放入函数中以查找数字的因子。从那里我试图找到素数的因素?这就是我到目前为止所拥有的。

enter code here####################################
n = int(input("Enter the n value"))
num = sum(10**x for x in range(n))
print("S",n,"is", num)
#####################################
# Factors 
#function name nfactors
def nfactors(x):
   # This function takes a number and prints the factors
  print("The factors of",x,"are:")
  for i in range(1, x + 1):
      if x % i == 0:
          print(i)

fact = nfactors(num)
print(fact)
#####################################
print('The prime numbers are:')

if fact > 1:
   # check for factors
   for i in range(2,fact):
       if (fact % i) == 0:

           break
   else:
       print(fact)

我知道这是糟糕的编程,但我正在尝试通过这个项目来学习。然后我如何将我收到的因子作为函数的输出并找出哪些因子是素数。我无法弄清楚如何在函数内部命名变量并在函数外部使用它,我不知道这是否可能。如果您需要任何说明,请告诉我。谢谢你的帮助。

python python-3.x function variables
2个回答
0
投票
def nfactors(x):
# This function takes a number and prints the factors
print("The factors of",x,"are:")
for i in range(1, x + 1):
    if x % i == 0:
        print(i)
        return i 

fact = nfactors(num)

使用return关键字返回i的值或者您希望在函数外使用的任何值!


0
投票

我真的希望你试图找到n而不是num的因素,因为只需要数量n=12就可以找到num的因子,即使我的优化代码也需要几分钟甚至几小时。

无论如何,假设你想为n而不是num找到它,下面的代码应该可以完成你的工作。

如果你真的想找到num的因子,这段代码也可以正常工作,但这需要花费太多时间。只需将factors = factors(n)更改为factors = factors(num)

from math import sqrt
#Block 1 (Correct)
n = int(input("Enter the n value"))
num = sum(10**x for x in range(n))
print("S",n,"is", num)

#---------------------------------------------------

def factors_(x):
    # This function takes a number and prints the factors
    print("The factors of",x,"are:")
    list_of_factors = []
    for i in range(1, x + 1):
        if x % i == 0:
            list_of_factors.append(i)
    return(list_of_factors) #This returns a list of factors of a given number x

factors = factors_(n) #I am assuming you want to find the prime factors of n instead of num
print(factors)

#------------------------------------------------------------------------------------

def is_prime(num): #This function returns True(1) if the number is prime else Flase(0)
    if num == 2:return 1
    if num%2 == 0:return 0
    i = 3
    while i < int(round(sqrt(num)) + 1):
        if num % i == 0:return 0
        i += 2
    return 1
#---------------------------------------------------------------------------------------    
prime_factors = []
for i in factors:
    if is_prime(i):
        prime_factors.append(i)

print("The prime factors of the numbers are:")
print(prime_factors)
© www.soinside.com 2019 - 2024. All rights reserved.