Python 在函数中定义变量
我的代码有点问题,它一直在说Python 在函数中定义变量,python,function,undefined,Python,Function,Undefined,我的代码有点问题,它一直在说 NameError: name 'km' is not defined 我在函数中定义了它。 如果我使用choice函数来做这件事会更好吗 def userinput(): while True: try: km = int(input("Enter the amount of kilometres you need (1 or 2)")) break except Value
NameError: name 'km' is not defined
我在函数中定义了它。
如果我使用choice函数来做这件事会更好吗
def userinput():
while True:
try:
km = int(input("Enter the amount of kilometres you need (1 or 2)"))
break
except ValueError:
print ("Oops! That was no valid number. Try again...")
return
userinput()
if km >= 3:
userinput()
if km <= 0:
userinput()
if km == 1:
zone = 0.01862
if km == 2:
zone = 0.02
def userinput():
尽管如此:
尝试:
km=int(输入(“输入所需的公里数(1或2)”)
打破
除值错误外:
打印(“哦!那不是有效的数字。请重试…”)
返回
用户输入()
如果公里数>=3:
用户输入()
如果公里数请尝试以下操作:
def userinput():
while True:
try:
km = int(input("Enter the amount of kilometres you need (1 or 2)"))
break
except ValueError:
print ("Oops! That was no valid number. Try again...")
return km
km = userinput()
if km >= 3:
km = userinput()
if km <= 0:
km = userinput()
if km == 1:
zone = 0.01862
if km == 2:
zone = 0.02
def userinput():
尽管如此:
尝试:
km=int(输入(“输入所需的公里数(1或2)”)
打破
除值错误外:
打印(“哦!那不是有效的数字。请重试…”)
返回公里
km=用户输入()
如果公里数>=3:
km=用户输入()
如果km变量仅在其首次声明的范围内可见