简体   繁体   中英

Regarding the def and return function in python

I was writing a program to write the multiplication table of number given by the user. Here's my code:

def mul_table(n):
    for i in range(1,11):
        print(n,"x",i,"=",(n * i))
        i = i + 1
    return(n)
        

x = int(input("Enter the number: "))
x1 = mul_table(x)
print(x1)

But in the output it shows the number entered by the user also in the end like this (I know have written the value after "return" but if I leave it empty then it shows None, so how can I get rid of this?):

Enter the number: 5
5 x 1 = 5  
5 x 2 = 10 
5 x 3 = 15 
5 x 4 = 20 
5 x 5 = 25 
5 x 6 = 30 
5 x 7 = 35 
5 x 8 = 40 
5 x 9 = 45 
5 x 10 = 50
**5**

Can anyone tell me that how can the program return nothing (absolutely nothing, not even the "None" text or the number entered by the user) in PYTHON 3.9.1?

Your mul_table function handles the printing itself. It needs no return value, and you shouldn't print it even if it exists - you should just call the function:

def mul_table(n):
    for i in range(1,11):
        print(n,"x",i,"=",(n * i))
        i = i + 1
    # return statement removed here        

x = int(input("Enter the number: "))
mul_table(x) # No need to capture the return value or print it

The problem is that mul_table method is returning n and you are printing it with print(x1) . Remove this call to print if you don't need it.

There are several issues, here is a working version

def mul_table(n):
    for i in range(1,11):
        print(n,"x",i,"=",(n * i))

x = int(input("Enter the number: "))
mul_table(x)
  1. You print inside the function, so you don't need to call mul_table in a print statement
  2. You also don't need a return statement in the function (though it returns None if you omit the return statement or use a return statement without a return value)
  3. i = i+1 inside the function is wrong, you are using a for statement where i gets values 1, 2, ..., 10 successively.

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