簡體   English   中英

有沒有更好的方法來編寫這段代碼,我應該在 function 原型之前有全局變量嗎?

[英]Is there a better way to write this code, should I have the global variables before the function prototype instead?

該代碼應該從用戶那里獲取兩個輸入,然后將它們相加。 如果結果在 15 到 20 之間,它應該打印“20”,如果是其他結果,它應該打印准確的總和答案。

def mysum (x,y):

total = x+y

if total in range (15,20):

    print ('20')

else:

    print (total)

x = int(input("Input the number:  "))
y = int(input("Input the number:  "))
mysum(x,y)

我不確定您是否可以說這更好,但這里有兩種不同的方法:

在這里,我做的和你做的完全一樣,但時間短一點:(也許也不太清楚?)

def mysum(x, y):
  print("20" if 15 <= x+y < 20 else str(x + y))

x = int(input("Input the number:  "))
y = int(input("Input the number:  "))
mysum(x,y)

在那里,我將所有內容都放在了mysum function 中(並使用了第一種方式的較短語法):

def mysum(): # No arguments
  x = int(input("Input the number:  "))
  y = int(input("Input the number:  "))
  print("20" if 15 <= x+y < 20 else str(x + y))

mysum()

請注意, mysum function 不再需要 arguments 這種方式。 也許你更喜歡那樣,也許你不喜歡(例如,因為你想在后面的代碼中重用xy )。

暫無
暫無

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

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