簡體   English   中英

關於 python 中的 def 和返回 function

[英]Regarding the def and return function in python

我正在編寫一個程序來編寫用戶給出的數字乘法表。 這是我的代碼:

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)

但是在 output 中,它最后也顯示了用戶輸入的數字(我知道在“return”之后寫了值,但如果我把它留空,那么它顯示為 None,那么我該如何擺脫這個?) :

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**

誰能告訴我,程序如何在 PYTHON 3.9.1 中什么都不返回(絕對沒有,甚至沒有“無”文本或用戶輸入的數字)?

您的mul_table function 處理打印本身。 它不需要返回值,即使它存在也不應該打印它——你應該調用 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

問題是mul_table方法正在返回n並且您正在使用print(x1)打印它。 如果不需要,請刪除此調用以print

有幾個問題,這是一個工作版本

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. 您在 function 內打印,因此您不需要在打印語句中調用mul_table
  2. 您也不需要 function 中的return語句(盡管如果您省略 return 語句或使用沒有返回值的 return 語句,它會返回 None )
  3. function 中的i = i+1是錯誤的,您正在使用 for 語句,其中i連續獲取值 1、2、...、10。

暫無
暫無

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

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