简体   繁体   中英

Can't figure out how to make my funtion not return None in Python

I have a program I am trying to make which will either show all the factors of a number or say it is prime. It's a simple program but I have one main issue. Once it prints all of the factors of an inputted number, it always returns none. I have tried multiple ways to get rid of it but nothing works without screwing something else up. The code is below.

def mys(x):
    x = input("Enter a number: ")
    for i in range(2,x):
        r = x % i
        if r == 0:
            print(i)
print(mys(x))

That code is just for printing the factors but that is where the problem lies. The results I get after entering a number, in this case 20, are as follows:

2
4
5
10
None

No matter what I do, I can't get the None to not print.

因此,如果您不希望不打印mys (None)的返回值,请不要打印它:

mys(x)

In python, a function that has no return statement always returns None.

I guess what you are trying to do is calling the mys function, and not printing it. Note that you should remove x parameter, because it is asked inside of the function.

def mys():
    x = input("Enter a number: ")
    for i in range(2,x):
        r = x % i
        if r == 0:
            print(i)
mys()

It would be better not to include user input and printing in your function. It would make it easier to test and to reuse:

def mys(x):
    result = []
    for i in range(2,x):
        r = x % i
        if r == 0:
            result.append(i)
    return result

x = input("Enter a number: ")
print(mys(x))

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