該代碼正在從用戶提供的低值和高值創建一個亂數。為什么,在函式內列印 comp_num 的值時,它回傳正確的值,但在序列末尾列印時,它是 0。
import random
comp_num = 0
def generateNumber():
comp_num = random.randint(low_number,high_number)
print(comp_num)
low_number = int(input("Please select the minimum number"))
high_number = int(input("Please select the high number"))
generateNumber()
print(f"The comp_num is {comp_num}")
uj5u.com熱心網友回復:
您需要在函式內部說它comp_num是一個global變數:
import random
comp_num = 0
def generateNumber():
global comp_num
comp_num = random.randint(low_number,high_number)
print(comp_num)
low_number = int(input("Please select the minimum number"))
high_number = int(input("Please select the high number"))
generateNumber()
print(f"The comp_num is {comp_num}")
輸出:
Please select the minimum number 2
Please select the high number 3
3
The comp_num is 3
uj5u.com熱心網友回復:
您還可以設計函式以回傳結果。更好地告訴函式它需要哪些輸入引數。
當您的代碼變大時,這是一種干凈的方法。此外,當您查看函式宣告時,您就會知道它的作用。
import random
def generateNumber(low: int, high: int) -> int:
return random.randint(low,high)
low_number = int(input("Please select the minimum number"))
high_number = int(input("Please select the high number"))
comp_num = generateNumber(low_number, high_number)
print(f"The comp_num is {comp_num}")
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/530842.html
標籤:Python变量范围
上一篇:無法通過eclipse連接到tomcat9進行遠程除錯
下一篇:清除BASH中設定的字串變數
