简体   繁体   English

如何从我的 output 中排除引号?

[英]How can I exclude the quotation marks from my output?

I need to write a function is_prime , to determine if n is a prime number, and if not I have to show the factors beginning with the smallest possible factor.我需要写一个 function is_prime来确定n是否是质数,如果不是,我必须以最小的可能因子开始显示因子。

It works however I need to exclude the quotation marks in the output otherwise I don't get any points for my homework.它可以工作,但是我需要排除 output 中的引号,否则我的作业不会得到任何分数。

def is_prime(n):
    pass

    if n > 1:
       for i in range(2,n):
           if (n % i) == 0:
               return(n,'is not a prime number', '(', i,'*',n//i,'=', n, ')')

               break
       else:
           return(n,'is prime')

    else:
       return(n,'is not a prime number')

print(is_prime(12))

Your problem is you are returning a list when you should return a string, you should use str.format() to return a string:你的问题是你应该返回一个字符串时返回一个列表,你应该使用 str.format() 返回一个字符串:

https://www.digitalocean.com/community/tutorials/how-to-use-string-formatters-in-python-3 https://www.digitalocean.com/community/tutorials/how-to-use-string-formatters-in-python-3

Also you do not need your 'break' nor 'else', because when you execute a return statement, your function end.此外,您不需要“break”或“else”,因为当您执行 return 语句时,您的 function 结束。

So if you found a divisor of n, you get into the return statement and the code after that is not executed.因此,如果您找到 n 的除数,您将进入 return 语句,之后的代码不会执行。

def is_prime(n):
    if n > 1:
        for i in range(2, n):
            if (n % i) == 0:
                return('{n} is not a prime number ({i} * {q} = {n})'.format(n=n, i=i, q=n//i))
        return('{n} is prime'.format(n=n))
    return('{n} is not a prime number'.format(n=n))

print(is_prime(15))

Instead of using comma (,) in your return statement, replace it with plus sign (+) and convert all your number value into string using str() function.不要在 return 语句中使用逗号 (,),而是用加号 (+) 替换它,并使用 str() function 将所有数字值转换为字符串。

def is_prime(n):
    pass

    if n > 1:
       for i in range(2,n):
           if (n % i) == 0:
               return(str(n) + ' is not a prime number ' + '(' + str(i) + '*' + 
str(n//i) + '=' + str(n) + ')')

               break
       else:
           return(n + 'is prime')

    else:
       return(n + 'is not a prime number')

print(is_prime(12))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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